手把手教你实现web页面内容滑动效果
web前端开发
共 2167字,需浏览 5分钟
·
2020-07-28 16:09
事件监听
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);
}
"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);
}
}
本文完~
评论