![35dc92a1946934bfaae14acc070ca52b.png](https://i-blog.csdnimg.cn/blog_migrate/8a72fd59c5903f9ed187f7bd10c83407.jpeg)
作者 | 唐宋元明清2188
来源 | http://www.cnblogs.com/kybs0/
标签的触摸/鼠标滑动事件,添加元素的切换动画,效果如下:
事件监听
鼠标事件和触摸事件监听:
componentDidMount() {
var teachingReportDiv = document.getElementById("teachingReport") as HTMLElement;
teachingReportDiv.onmousedown = this.onMouseDown;
teachingReportDiv.onmouseup = this.onMouseUp;
teachingReportDiv.addEventListener('touchstart', this.onTouchStart, false);
teachingReportDiv.addEventListener('touchmove', this.onTouchMove, false);
teachingReportDiv.addEventListener('touchend', this.onTouchEnd, false);
}
触摸事件,不能HTMLElement.ontouchstart添加事件监听,可以EventListener或者在标签中添加。
"teachingReport" onTouchStart={(event) => this.onTouchStart(event)}/>触摸事件有以下几个:
touchstart
事件:手指触摸时候触发(支持多指触发)touchmove
事件:手指在滑动的时候连续地触发。在这个事件发生期间,调用preventDefault()
事件可以阻止滚动,当然也不能滥用否则会影响原有页面的上下滚动等。touchend
事件:手指从屏幕上离开的时候触发touchcancel
事件:当系统停止跟踪触摸的时候触发。关于这个事件的确切出发时间,文档中并没有具体说明。。。不建议使用
事件处理
添加全局字段:
locationStartX: number = 0;
locationEndX: number = 0;
滑动处理,超出滑动阈值后,更新相关状态。
onTouchStart = (event) => {
this.locationStartX = event.targetTouches[0].pageX;
}
onTouchMove = (event) => {
// event.preventDefault();
this.locationEndX = event.targetTouches[0].pageX;
}
onTouchEnd = (event) => {
const locationChangedX = this.locationEndX < this.locationStartX;
if (Math.abs(locationChangedX) > 10) {
const isSlidingToRight=locationChangedX<0;
}
}
添加切换动画
动画,可以通过state参数触发
this.onTouchStart(event)}/>动画数据参考://动画
@keyframes showFromLeft {
from {
opacity: 0;
transform: translateX(-100px);
}
to {
opacity: 1;
transform: translateX(0px);
}
}
@keyframes showFromRight {
from {
opacity: 0;
transform: translateX(100px);
}
to {
opacity: 1;
transform: translateX(0px);
}
}
@keyframes hideToLeft {
from {
opacity: 1;
transform: translateX(0px);
}
to {
opacity: 0;
transform: translateX(-100px);
}
}
@keyframes hideToRight {
from {
opacity: 1;
transform: translateX(0px);
}
to {
opacity: 0;
transform: translateX(100px);
}
}
本文完~![958d3be82dc79293857a52563b6c7949.png](https://i-blog.csdnimg.cn/blog_migrate/69239ff476e478101789ae414c2d3e84.jpeg)
![9c5732f0d169c41380e2b536c3372b50.png](https://i-blog.csdnimg.cn/blog_migrate/02fc8077a223a8e51d4665274b457484.png)