After clicking the carousel, I can observe a short delay until the element holding the 'active' class changes.
(单击轮播之后,我可以观察到短暂的延迟,直到拥有“活动”类的元素发生变化。)
I imagine the class applies after the specified transition of the carousel's scroll animation.(我想象该类在轮播的滚动动画的指定过渡之后适用。)
(Some information on that here: https://materializecss.com/carousel.html )((有关此信息,请参见: https : //materializecss.com/carousel.html ))
I can't see an event listener provided by materialize for carousel scroll animation completion, so you might have to create your own workaround.
(我看不到materialize为轮播滚动动画完成提供的事件侦听器,因此您可能必须创建自己的解决方法。)
You could use setTimeout on your 'click' event listener, to check which element contains the 'active' class after the transition period.(您可以在“点击”事件监听器上使用setTimeout,以检查过渡期之后哪个元素包含“活动”类。)
(But setTimeout is not accurately timed, so make sure you add a 100ms or so.)((但是setTimeout的计时不准确,因此请确保添加100ms左右。))
function activeElementChanged() {
let newElement = $("a.carousel-item.active")
let itemId = newElement.find("img.responsive-img").attr("itemid")
console.log("ID: ", itemId)
}
$(".carousel").click(function( event ) {
setTimeout(activeElementChanged, 400)
}
Or you could use requestAnimationFrame to iterate continuously, checking if the active element has changed without listening for a click and without freezing the page's main thread.
(或者,您可以使用requestAnimationFrame进行连续迭代,检查活动元素是否已更改,而无需侦听单击,也无需冻结页面的主线程。)
let activeElement = null
function activeElementChanged(newElement) {
activeElement = newElement
let itemId = newElement.find("img.responsive-img").attr("itemid")
console.log("ID: ", itemId)
}
let activeElementListener = function () {
let currentActiveElement = $("a.carousel-item.active")
if(currentActiveElement !== activeElement) {
activeElementChanged(currentActiveElement)
}
requestAnimationFrame(activeElementListener)
}
requestAnimationFrame(activeElementListener)
EDIT: I just noticed you can get the index of the currently centered item using the materlize API.
(编辑:我刚刚注意到您可以使用materlize API获取当前居中项的索引。)
This should update straight after clicking without a delay.(单击后应立即更新。)
I also fixed some issues with the previous code.(我还修复了先前代码的一些问题。)
let carouselElement = $(".carousel")
let carousel = M.Carousel.getInstance(carouselElement);
let numberOfItems = ...
$(".carousel").click(function( event ) {
let itemIndex = carousel.center
while(itemIndex < 0)
itemIndex += numberOfItems
while(itemIndex >= numberOfItems)
itemIndex -= numberOfItems
let itemId = itemIndex + 1
console.log("ID: ", itemId)
}
The 'center' property starts at zero and doesn't cycle (it goes infinitely negative as you scroll left, and infinitely positive as you go right), so you have to adjust it as shown above to get the itemId you are looking for.
(“居中”属性从零开始并且不循环(当您向左滚动时,它变为无限负数,而当您向右滚动时,它变为无限正数),因此您必须如上所示对其进行调整,以获取所需的itemId。)