设置 HTML 中的属性时,滑动滑块将类添加到活动幻灯片

2022-01-24 00:00:00 slider jquery javascript html swiper

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

I want to add class to navbar when active slide has got attribute set for example "navbar-dark". I tried with class but my function doesn't work perfect. It is when I changed slide the class was adding to the second slide not to first slide.

$(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');
        }
    });
});

推荐答案

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

I googled for "swiper jQuery plugin", opened the first suggested page and went to the API. And there's the Events section, and there's the .on init method. Let's try it

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.swiper-slide-active').hasClass('dark')('.swiper-slide-active').hasClass('dark')

Also, instead of $('.swiper-slide.swiper-slide-active').hasClass('dark') you could rather try with $(this).find('.swiper-slide-active').hasClass('dark')

相关文章