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

Swiper slider add class to active slide when attribute in HTML is set(设置 HTML 中的属性时,滑动滑块将类添加到活动幻灯片)

本文介绍了设置 HTML 中的属性时,滑动滑块将类添加到活动幻灯片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当活动幻灯片设置了属性(例如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')

这篇关于设置 HTML 中的属性时,滑动滑块将类添加到活动幻灯片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:设置 HTML 中的属性时,滑动滑块将类添加到活动幻灯片

基础教程推荐