如何设置“滑动”滑块中边缘上的幻灯片的样式

时间:2019-11-07 10:57:21

标签: javascript css swiper

我正在使用Swiper滑块插件(https://swiperjs.com)。我需要将不透明度0.5添加到可见视口边缘的幻灯片上。 https://i.stack.imgur.com/A6nr5.png

我发现我可以使用此选择器选择合适的幻灯片,并在可见幻灯片数量发生变化时通过媒体查询对其进行更改:

.swiper-slide-active + * + * + * {
      opacity: 0.5;
}

但是此技巧不适用于左侧的幻灯片。我想不仅有CSS解决方案,还必须使用JS来检测可见的幻灯片吗?

const specialSlider = new Swiper('.special-slider', {
    loop: true,
    speed: 1000,
    slidesPerView: 'auto',
    spaceBetween: 30,
    centeredSlides: true,

    navigation: {
      nextEl: '.special-slider__next',
      prevEl: '.special-slider__prev',
    },
    watchOverflow: true,
    grabCursor: true,

  });

2 个答案:

答案 0 :(得分:1)

这很容易,swiper帮您完成繁重的工作。只需将其添加到您的滑动设置中即可:

watchSlidesVisibility: true

现在,您可以使用swiper-slide-visible类来设置可见幻灯片的样式。

例如:

.swiper-slide {
  opacity: .25;
}
.swiper-slide-visible {
  opacity: 1;
}

请记住,很容易更改每个类的名称空间:

slideClass: 'myslider__slide',
slideVisibleClass: 'myslider__slide--visible'

更新

Example on Codepen

更新2

Example (only 1 edge) on Codepen

答案 1 :(得分:0)

这是我发现的解决方案:

function b()
{
  rotAllowed = true;
}

和样式:

const specialSlider = new Swiper('.special-slider', {
    loop: true,
    speed: 1000,
    slidesPerView: 'auto',
    spaceBetween: 0,
    centeredSlides: true,

    navigation: {
      nextEl: '.special-slider__next',
      prevEl: '.special-slider__prev',
    },
    watchOverflow: true,
    grabCursor: true,

    on: {

      init: makeSlidesTransparent,
      slideChangeTransitionStart: makeSlidesTransparent,
    }

  });

  function makeSlidesTransparent() {

    //Hide old slides
    const oldSlides = d.getAll('.special-slider__item.js-visible');
    for (let i = 0; i < oldSlides.length; i++) {
      oldSlides[i].classList.remove('js-visible')
    }

    const width = window.innerWidth;

    if (width >= 0 && width < 960) {
      //Make visible new slides
      const activeSlide = d.get('.special-slider__item.swiper-slide-active');
      activeSlide.classList.add('js-visible');
    }

    if (width >= 960 && width < 1700) {
      //Make visible new slides
      const activeSlide = d.get('.special-slider__item.swiper-slide-active');
      const prev1 = activeSlide.previousElementSibling;
      const next1 = activeSlide.nextElementSibling;

      prev1.classList.add('js-visible');
      activeSlide.classList.add('js-visible');
      next1.classList.add('js-visible');
    }

    if (width >= 1700) {
      //Make visible new slides
      const activeSlide = d.get('.special-slider__item.swiper-slide-active');
      const prev1 = activeSlide.previousElementSibling;
      const prev2 = prev1.previousElementSibling;
      const next1 = activeSlide.nextElementSibling;
      const next2 = next1.nextElementSibling;

      prev1.classList.add('js-visible');
      prev2.classList.add('js-visible');
      activeSlide.classList.add('js-visible');
      next1.classList.add('js-visible');
      next2.classList.add('js-visible');
    }

  }