繁体   English   中英

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

[英]Why does function clearInterval() not working? I used setInterval too

我正在创建一个产品悬停效果,我使用了 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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM