Javascript 如何获取OwlCarousel2中上一项和下一项的索引?
如何在OwlCarousel中获取下一个和上一个项目的索引,以便为下一个和上一个按钮设置背景图像?我制作了旋转木马的基本变体Javascript 如何获取OwlCarousel2中上一项和下一项的索引?,javascript,jquery,carousel,slideshow,owl-carousel-2,Javascript,Jquery,Carousel,Slideshow,Owl Carousel 2,如何在OwlCarousel中获取下一个和上一个项目的索引,以便为下一个和上一个按钮设置背景图像?我制作了旋转木马的基本变体 $('.cat-slides').owlCarousel({ items: 1, center: true, loop: true, autoWidth:true, }); 我需要获取上一个和下一个的索引,以便将img设置为上一个和下一个按钮的背景。尝试下面的代码获取索引 var owl = $('.cat-slides'); owl.o
$('.cat-slides').owlCarousel({
items: 1,
center: true,
loop: true,
autoWidth:true,
});
我需要获取上一个和下一个的索引,以便将img设置为上一个和下一个按钮的背景。尝试下面的代码获取索引
var owl = $('.cat-slides');
owl.owlCarousel();
owl.on('changed.owl.carousel', function (e) {
var currentindex = e.item.index;
return currentindex;
});
首先,有必要了解这个转盘库生成幻灯片的“克隆”,将一半克隆放在幻灯片之前,其余克隆放在幻灯片之后。这是一个包含12项的示例: 因此,要获得与活动项相关的按钮的正确索引,需要从活动项的索引中减去克隆数的一半。以下是您的做法:
$(".cat-slides").on('changed.owl.carousel', function() {
// get the index of the active item
const activeItem = document.querySelector('.owl-carousel.cat-slides .active');
const allItems = Array.from(activeItem.parentNode.children);
const index = allItems.indexOf(activeItem);
// count the clones
const cloneCount = activeItem.parentNode.querySelectorAll('.cloned').length;
// take the previous/next item's index, then subtract half the clones from it
const prevButtonIndex = index - 1 - cloneCount / 2;
const nextButtonIndex = index + 1 - cloneCount / 2;
// get references to the next and previous button elements
const allButtons = document.querySelectorAll('.owl-dot');
const nextButton = allButtons[nextButtonIndex];
const prevButton = allButtons[prevButtonIndex];
// example of how you'd change the background image of each button
if (nextButton) nextButton.style.backgroundImage = "path/to/next/image";
if (prevButton) prevButton.style.backgroundImage = "path/to/prev/image";
});
你缺少的下一点是如何获得上一张/下一张图片,但我只是回答你提出的问题。如果有什么不清楚的地方,请告诉我。是我做的。现在,我尝试获取prev&next索引(我现在了解inc和dec),以便为prev&next按钮设置背景图像。