轮播组件中addEventListener('animationend')触发两次问题排查
问题原因
你遇到的animationend事件触发两次的问题,核心原因是重复给同一个轮播元素添加了事件监听器。每次该元素成为当前活跃项时,你都会为它绑定一个新的animationend监听器,但之前绑定的监听器并没有被移除。当动画结束时,所有累积的监听器都会触发,导致回调函数多次执行。
解决方案
方案1:使用once选项(最简单)
在添加事件监听器时,传入{once: true}参数。这个参数会让监听器在触发一次后自动移除自身,避免重复绑定:
squares[currentItem].addEventListener('animationend', function(){ console.log(currentItem) squares[currentItem].classList.remove('toLeft') squares[((currentItem+1)+squares.length) % squares.length].classList.remove('fromRight') squares[currentItem].classList.add('hide') changeCurrentItem(currentItem+1) }, {once: true});
方案2:手动移除监听器
如果需要更灵活的控制,可以将回调函数定义为命名函数,在执行完毕后手动移除监听器:
function handleAnimationEnd() { console.log(currentItem) squares[currentItem].classList.remove('toLeft') squares[((currentItem+1)+squares.length) % squares.length].classList.remove('fromRight') squares[currentItem].classList.add('hide') changeCurrentItem(currentItem+1) // 执行后移除监听器 squares[currentItem].removeEventListener('animationend', handleAnimationEnd); } // 绑定监听器 squares[currentItem].addEventListener('animationend', handleAnimationEnd);
内容的提问来源于stack exchange,提问作者Sundozer
相关产品推荐
相关产品推荐

