为什么函数clearInterval()不起作用?我也使用了setInterval



我正在创建一个产品悬停效果,其中我使用了mouseover和mouseleave函数。然而,我目前在Javascript上的clearInterval函数上遇到了问题。我错过什么了吗?该结构也对齐。这是我的代码:

<script>
document.addEventListener("DOMContentLoaded", ()=>{
// //get img url from span
// const src = spanElem.attr('data-original');
// //change span to img using the value from data-original
// spanElem.replaceWith('<img class="product-img-toadd w3-animate-fading" src="' + src + '"/>');

const imgGallery = document.querySelectorAll('.product-img-gallery');

const imageDiv = document.querySelectorAll('.product-tile__image');
let interval
imageDiv.forEach(el=>{
//img
const imgGalleryItem = el.querySelectorAll('.product-img-gallery__item')
el.addEventListener("mouseenter", ()=>{
imgGalleryItem.forEach(item=>{
const src = item.getAttribute('data-original')
const img = `<img class="product-img-toadd w3-animate-fading" src="${src}"/>`
item.insertAdjacentHTML('beforeend',img)

//slider
const imgSlides = el.querySelectorAll('.product-img-toadd');
let currentIndex = 0
interval = setInterval(() => {
imgSlides.forEach((item) => {
item.style.opacity = 0;
});
imgSlides[currentIndex].style.opacity = 1;
if (currentIndex === imgSlides.length - 1) {
currentIndex = 0;
} else {
currentIndex = currentIndex + 1;
}
console.log("tick")
}, 750);
})
})
el.addEventListener("mouseleave", ()=>{
const imgSlides = el.querySelectorAll('.product-img-toadd');
imgSlides.forEach((item) => {
item.style.opacity = 0;         
});
clearInterval(interval);
})
})
})

您在循环中分配interval,用下一个元素覆盖前一个元素。

一个可能的解决方案是将每个间隔推送到一个数组中,然后遍历所有元素并清除其中的元素。

let intervals = [];
intervals.push( setInterval(() => { ... });
...
intervals.forEach((iv) => clearInterval(iv));

相关内容

最新更新