【问题标题】:Swiper slider add class to active slide when attribute in HTML is set设置 HTML 中的属性时,滑动滑块将类添加到活动幻灯片
【发布时间】:2019-02-20 17:42:57
【问题描述】:

当活动幻灯片设置了属性(例如“navbar-dark”)时,我想向导航栏添加类。我尝试过上课,但我的功能并不完美。当我更改幻灯片时,班级将添加到第二张幻灯片而不是第一张幻灯片。

$(document).ready(function () {
    var mySwiper = new Swiper('.swiper-container', {
        direction: 'horizontal',
        loop: false,
        mousewheel: {
            invert: false,
        },
    });
    mySwiper.on('slideChange', function (realIndex) {
        if ($('.swiper-slide.swiper-slide-active').hasClass('dark')) {
            $('#navbar').addClass('darknav')
        } else {
            $('#navbar').removeClass('darknav');
        }
    });
});

【问题讨论】:

    标签: javascript jquery html slider swiper


    【解决方案1】:

    我在 Google 上搜索“swiper jQuery 插件”,打开第一个建议页面并转到 the API。 还有Events section,还有.on init 方法。让我们试试吧

    jQuery(function($) {
    
      function darkNav() {
        //if ( $('.swiper-slide.swiper-slide-active').hasClass('dark') ) { // `this` rather?
        if ( $(this).find('.swiper-slide-active').hasClass('dark') ) {
          $('#navbar').addClass('darknav')
        } else {
          $('#navbar').removeClass('darknav');
        }
      }
    
      var mySwiper = new Swiper('.swiper-container', {
        direction: 'horizontal',
        loop: false,
        mousewheel: {
          invert: false,
        },
        on: {
          init: darkNav,          // do also on init
          slideChange: darkNav    // is this needed?
        }
      });
    
    });

    另外,您可以尝试使用$(this).find('.swiper-slide-active').hasClass('dark'),而不是$('.swiper-slide.swiper-slide-active').hasClass('dark')

    【讨论】:

    • 有了你,我实现了我想要的。非常感谢您。我只将“slideChange”更改为“slideChangeTransitionStart”,一切正常。
    猜你喜欢
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2017-02-16
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多