X事件中使用transitionend,为什么会触发到Y事件的transitionend?

我用JS写一个全屏滚动的demo,其中执行了上滚函数的transitionend会触发到下滚函数的transitionend这是什么原因?

具体说明如下:
如果鼠标下滚了,就修改一个DOM元素的top。
元素绑定了一个类作为过渡,当过渡动画完成执行transitionend。

如果鼠标上滚了,就修改上一个DOM元素的top。
元素绑定了一个类作为过渡,当过渡动画完成执行transitionend。

相关代码

if (dir == "down") {

        this.ScrollDown(() => {
          console.log("开始下滚,当前currentPage为"+this.currentPage);
          let oWrap = document.getElementById("wrap");
          let aDiv = oWrap.getElementsByTagName("div"); //获取到4个DIV
          
          let el = aDiv[this.currentPage]; //currentPage=0,此时获取到第1个DIV
          el.style.top = -this.WebHeight + 'px'; //进行样式操作

          el.addEventListener("transitionend", () => {  //CSS动画完成后
            this.currentPage++; //数据++ ; currentPage=1
            console.log("第一次下滚完成,当前currentPage为"+this.currentPage);
          }, false)
        });
      } else {
        this.ScrollUp(() => {
           console.log("开始上滚,当前currentPage为"+this.currentPage);
          let oWrap = document.getElementById("wrap");
          let aDiv = oWrap.getElementsByTagName("div"); //获取到4个DIV
          
          let el = aDiv[this.currentPage-1]; //1-1=0 ; 获取到上一个已经进行样式操作的DIV
          el.style.top = 0; //进行样式操作,top值变回原样

          el.addEventListener("transitionend", () => {  //CSS动画完成后
            this.currentPage--; //数据++
            console.log("第一次上滚完成,当前currentPage为"+this.currentPage);
          }, false)
        });
      }

实际运行结果


执行第一次下滚的时候没有问题
图片描述
执行第一次上滚的时候,会触发到下滚的transitionend,试currentPage值++了,这是为什么?

阅读 1.8k
1 个回答

滚动之后page++,再反方向滚动,那时候的page-1不就是之前的page吗?所以你是在给同一个元素添加事件,当然会触发2次了。而且如果你来回滚动几次,你会发现每次触发的次数会越来越多

推荐问题