![](/img/trans.png)
[英]How to add event listeners to multiple elements with the same class and then only change CSS for specific other element
[英]How to add class on the first & last element that has specific class inside multiple same elements class?
我試圖在第一個和最后一個子元素的 class 上添加 class 和 ONLY.active class。 我在這里找到了代碼:
jQuery(document).ready(function($) {
var carousel = $(".latest-work-carousel");
carousel.owlCarousel({
loop : true,
items : 3,
margin:0,
nav : true,
dots : false,
});
checkClasses();
carousel.on('translated.owl.carousel', function(event) {
checkClasses();
});
function checkClasses(){
var total = $('.latest-work-carousel .owl-stage .owl-item.active').length;
$('.latest-work-carousel .owl-stage .owl-item').removeClass('firstActiveItem lastActiveItem');
$('.latest-work-carousel .owl-stage .owl-item.active').each(function(index){
if (index === 0) {
// this is the first one
$(this).addClass('firstActiveItem');
}
if (index === total - 1 && total>1) {
// this is the last one
$(this).addClass('lastActiveItem');
}
});
}
});
它確實有效,但是我的問題是firstActiveItem class 僅應用於第一個輪播內部,而lastActiveItem class 應用於第二個輪播內部。
無論我有多少個帶有相同 class 的旋轉木馬,我如何使它適用於所有旋轉木馬?
這是我完整的代碼小提琴: https://jsfiddle.net/tarantadakadin101/xf54zsau/39/
條件應該是:
if (index === 0 || index === total / 2) {
// this is the first one
$(this).addClass('firstActiveItem'); // add class in first item
}
if ((index === total - 1 && total) > 1 || index === total / 2 - 1) {
// this is the last one
$(this).addClass('lastActiveItem'); // add class in last item
}
這是鏈接
您可以迭代.owl-carousel
元素並在每次迭代時從當前.owl-carousel
的子元素中找到目標元素。 使用這種方法,無論頁面上存在多少輪播。 像這樣:
$('.owl-carousel').each(function(){
$(this).find('.owl-stage .owl-item.active:first').addClass('firstActiveItem');
$(this).find('.owl-stage .owl-item.active:last').addClass('lastActiveItem');
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.