如何使用 jQuery 查找具有动态更新的"活动"类而没有单击事件的元素?



我的网页上有一个具体的css轮播。当轮播旋转到上一个/下一个链接时,焦点链接上的类将从class = "carousel-item active"更改为class = "carousel-item"

我的目标是使用 jQuery 来识别新的active类并显示与该图像相关的相应文本。

我尝试使用.mousemove()事件侦听器无济于事。

我正在通过将焦点图像的itemid记录到控制台来测试这一点。在页面加载时,将记录正确的itemid。但是,当我向左或向右滚动轮播时,新itemid不会记录,也不会发生任何反应。

我也尝试使用hasClass().我的困惑不在于如何识别或抓取元素。它是如何让选择器持续侦听,以便当一个图像丢失active类而另一个图像现在具有active类时,将显示相应的文本。

以下是我引用的项目页面的链接:http://www.alexandervellios.com/projects.html

这是我的轮播的代码片段:

<div class= "carousel" id="fs">
<a class="carousel-item" href="https://butterflysocial.herokuapp.com/"><img src="../img/butterfly.jpg" itemid="1" class="responsive-img">
<h6 class= "carouselTitle white-text">Butterfly Social</h6>
</a>
<a class="carousel-item" href="https://bleauwonder.github.io/renegades-of-silicon-alley/"><img src="../img/compass.jpg" itemid="2" class="responsive-img">
<h6 class= "carouselTitle white-text">Renegade TrailBrews</h6>
</a>
</div>

这是带有active类的浏览器上的代码图像

更新: 我已经将click()事件侦听器添加到我的 jQuery 中,代码现在正在注册更改。但是,它仍然只记录初始itemid1。我不是没有适当地抓住子元素吗?

以下是使用.click()事件侦听器的更新 jQuery:

$(".carousel").click(function( event ) {
if($("a.carousel-item").hasClass("active")) {
let itemId = $("img.responsive-img").attr("itemid")
console.log("ID: ", itemId)
}
})

单击轮播后,我可以观察到短暂的延迟,直到包含"活动"类的元素发生变化。我想该类在旋转木马滚动动画的指定过渡之后适用。 (关于这方面的一些信息:https://materializecss.com/carousel.html(

我看不到 Materialize 为轮播滚动动画完成提供的事件侦听器,因此您可能需要创建自己的解决方法。您可以在"click"事件侦听器上使用 setTimeout,以检查哪个元素在过渡期后包含"active"类。(但是 setTimeout 没有准确计时,因此请确保添加 100 毫秒左右。

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)
}

或者,您可以使用 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)

编辑: 我刚刚注意到您可以使用 materlize API 获取当前居中的项目的索引。这应该在单击后立即更新,没有延迟。 我还修复了以前代码的一些问题。

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)
}

"center"属性从零开始并且不循环(当你向左滚动时它会无限负,当你向右滚动时它会无限正(,所以你必须如上所示调整它以获得你要找的itemId。

最新更新