Swiper slider add class to active slide when attribute in HTML is set(设置 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 中的属性时,滑动滑块将类添加到活动幻灯片
基础教程推荐
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 我什么时候应该在导入时使用方括号 2022-01-01