swiper
swiper 9 焦点在第三张
let isClickEvent = false;
// const swiper = new Swiper('.swiper-container');
// Optional parameters
const swiper = new Swiper('.swiper-container', {
slidesPerView: 'auto',
// slideToClickedSlide:true,
spaceBetween: 12,
});
swiper.on('slideChange', function () {
if (isClickEvent) {
return;
}
isClickEvent = true;
const previousIndex = swiper.previousIndex;
const realIndex = swiper.realIndex;
console.log(previousIndex, realIndex);
const activeIndex = Array.from(swiper.slides).findIndex(el => el.classList.contains('active'));
const prevIndex = parseInt(activeIndex) - 1;
let nextIndex = parseInt(activeIndex) + 1;
if (previousIndex > realIndex) {
// 向前
swiper.slides[activeIndex].classList.remove('active');
swiper.slides[prevIndex].classList.add('active');
swiper.slideTo(prevIndex > 2 ? prevIndex - 2 : 0);
} else if (previousIndex < realIndex) {
if (nextIndex < 3) {
nextIndex = 3
}
// 向后
swiper.slides[activeIndex].classList.remove('active');
swiper.slides[nextIndex].classList.add('active');
swiper.slideTo(nextIndex > 2 ? nextIndex - 2 : 0);
}
setTimeout(() => {
isClickEvent = false;
}, 0);
});
// 点击切换slide
swiper.on('click', function () {
isClickEvent = true;
const clickedSlide = swiper.slides[swiper.clickedIndex];
if (!clickedSlide.classList.contains('active')) {
// document.querySelector('.swiper-slide.active')?.classList.remove('active');
swiper.wrapperEl.querySelector('.swiper-slide.active')?.classList.remove('active');
clickedSlide.classList.add('active');
}
swiper.slideTo(swiper.clickedIndex > 2 ? swiper.clickedIndex - 2 : 0);
// 重置标志变量为false
setTimeout(() => {
isClickEvent = false;
}, 0);
});