【问题标题】:How to detect if a particular slide with a class is in the view?如何检测具有类的特定幻灯片是否在视图中?
【发布时间】:2018-09-23 15:19:16
【问题描述】:

我已经初始化了 slidesPerView: 3slidesPerGroup: 3,并且我有一个名为 .section-xx-start 的类来分隔时间线中的每个“部分”,就像轮播一样,每次幻灯片都带有 .section-xx-start 类在视图中(无论哪个位置,1st 2nd 或 3rd),背景颜色都会发生变化。我似乎找不到为此的参数/方法。这是我目前所拥有的:

<div class="swiper-slide section-one-start">
    ...
</div>
<div class="swiper-slide">
    ...
</div>
<div class="swiper-slide">
    ...
</div>
<div class="swiper-slide">
    ...
</div>
<div class="swiper-slide">
    ...
</div>
<div class="swiper-slide section-two-start">
    ...
</div>

<script>
    var mySwiper = new Swiper ('.swiper-container', {
        slidesPerView: 3,
        slidesPerGroup: 3,
        spaceBetween: 50,
        grabCursor: true,
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        }
    });

    const nextButton = document.querySelector('.swiper-button-next');
    const prevButton = document.querySelector('.swiper-button-prev');

    function changeBgColor() {
       if(slideWithClassIsInViewPort) {
           this.style.backgroundColor = "var(--navy)";
       } else {
           //do nothing
       }
    }

    nextButton.addEventListener('click', changeBgColor);
    prevButton.addEventListener('click', changeBgColor);
</script>

我只是不确定如何应用“slideWithClassIsInViewPort”部分。如果有任何其他建议可以改进我的代码,请提出建议!感谢任何帮助!

编辑:访问(删除)以查看滑块。

【问题讨论】:

    标签: javascript html css slider swiper


    【解决方案1】:

    如果您使用 CSS 规则显示来隐藏/显示幻灯片,您可以只检查当前幻灯片的显示状态。

    例子:

    if(slide.style.display ='block'){
      // do whatever
    }
    

    编辑:

    我不确定你是否已经修复了它,但如果你没有修复,这里是你的 main.js 文件中的一个代码,它将滑块的当前索引记录到控制台。

    const button = document.querySelector('.swiper-button-next');
    
    function consoleLog() {
        console.log(mySwiper.activeIndex);
    }
    
    button.addEventListener('click', consoleLog);
    

    单击幻灯片中的下一步时,我假设显示的列数会出现。而且由于每张幻灯片每张显示 3 列,因此索引可能围绕它工作,有 3、6、9、12 等。因此,要设置不同的背景或您想要做的任何事情,对于每张幻灯片,您可以执行类似的操作这个:

    例子:

    var currentIndex = mySwiper.activeIndex;
    
    function changeBg(){
    if(currentIndex == 3) // second slide {
    slider.style.background='white';
    }
    if(currentIndex == 6) // third slide {
    slider.style.background='blue';
    } 
    
    button.addEventListener('click', changeBg);
    

    可能有更好的方法可以做到这一点,但我现在没有太多时间,所以这是我能做的最好的。

    【讨论】:

    • 我没有使用 CSS 显示规则来查看它是否处于活动状态。查看编辑以查看网站和滑块的 url。
    • 当我访问您的网站并单击滑块中的下一步时,它会执行一个将幻灯片的当前索引记录到控制台的功能,所以我想您已经修复了它。
    • 嘿,谢谢,我想差不多了!再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多