web 页面/内容滑动

 监听标签的触摸/鼠标滑动事件,添加元素的切换动画,效果如下:

事件监听

鼠标事件和触摸事件监听:

1     componentDidMount() {
2         var teachingReportDiv = document.getElementById("teachingReport") as HTMLElement;
3         teachingReportDiv.onmousedown = this.onMouseDown;
4         teachingReportDiv.onmouseup = this.onMouseUp;
5         teachingReportDiv.addEventListener('touchstart', this.onTouchStart, false);
6         teachingReportDiv.addEventListener('touchmove', this.onTouchMove, false);
7         teachingReportDiv.addEventListener('touchend', this.onTouchEnd, false);
8     }

触摸事件,不能HTMLElement.ontouchstart添加事件监听,可以EventListener或者在标签中添加

1    <div id="teachingReport" onTouchStart={(event) => this.onTouchStart(event)}/>

触摸事件有以下几个:

  • touchstart事件:手指触摸时候触发(支持多指触发)
  • touchmove事件:手指在滑动的时候连续地触发。在这个事件发生期间,调用preventDefault()事件可以阻止滚动,当然也不能滥用否则会影响原有页面的上下滚动等。
  • touchend事件:手指从屏幕上离开的时候触发
  • touchcancel事件:当系统停止跟踪触摸的时候触发。关于这个事件的确切出发时间,文档中并没有具体说明。。。不建议使用

事件处理

添加全局字段:

    locationStartX: number = 0;
    locationEndX: number = 0;
滑动处理,超出滑动阈值后,更新相关状态
 1     onTouchStart = (event) => {
 2         this.locationStartX = event.targetTouches[0].pageX;
 3     }
 4     onTouchMove = (event) => {
 5         // event.preventDefault();
 6         this.locationEndX = event.targetTouches[0].pageX;
 7     }
 8     onTouchEnd = (event) => {
 9         const locationChangedX = this.locationEndX < this.locationStartX;
10         if (Math.abs(locationChangedX) > 10) {
11             const isSlidingToRight=locationChangedX<0;
12         }
13     }

添加切换动画

动画,可以通过state参数触发

1 <div className="reportContent-img" style={{ animation: this.state.selectTabIndex == 0 ? 'showFromLeft 0.4s forwards' : 'hideToLeft 0.2s forwards' }}>div>

动画数据参考:

 1   //动画
 2   @keyframes showFromLeft {
 3     from {
 4       opacity: 0;
 5       transform: translateX(-100px);
 6     }
 7     to {
 8       opacity: 1;
 9       transform: translateX(0px);
10     }
11   }
12   @keyframes showFromRight {
13     from {
14       opacity: 0;
15       transform: translateX(100px);
16     }
17     to {
18       opacity: 1;
19       transform: translateX(0px);
20     }
21   }
22   @keyframes hideToLeft {
23     from {
24       opacity: 1;
25       transform: translateX(0px);
26     }
27     to {
28       opacity: 0;
29       transform: translateX(-100px);
30     }
31   }
32   @keyframes hideToRight {
33     from {
34       opacity: 1;
35       transform: translateX(0px);
36     }
37     to {
38       opacity: 0;
39       transform: translateX(100px);
40     }
41   }

 

你可能感兴趣的:(web 页面/内容滑动)