前言:本文主要给大家介绍一下移动端常用的事件和插件。
touchstart
:当手指触摸屏幕的时候触发touchmove
:当手指在屏幕来回的滑动时候触发touchend
: 当手指离开屏幕的时候触发touchcancel
:当被迫终止滑动的时候触发(来电,弹消息)box.addEventListener('touchstart',function () { });
changedTouches
:改变后的触摸点集合,每个事件发生都会记录触摸点targetTouches
:当前元素的触发点集合,在离开屏幕的时候无法记录触摸点touches
:页面上所有触发点集合,在离开屏幕的时候无法记录触摸点touchend
事件对象中的targetTouches
和touches
长度为0swipe
swipeLeft
swipeRight
swipeUp
swipeDown
window.onload = function () {
/*1. 理解移动端的手势事件*/
/*2. `swipe` `swipeLeft` `swipeRight` `swipeUp` `swipeDown` */
/*3. 左滑和右滑手势怎么实现*/
var bindSwipeEvent = function (dom,leftCallback,rightCallback) {
/*手势的条件*/
/*1.必须滑动过*/
/*2.滑动的距离50px*/
var isMove = false;
var startX = 0;
var distanceX = 0;
dom.addEventListener('touchstart',function (e) {
startX = e.touches[0].clientX;
});
dom.addEventListener('touchmove',function (e) {
isMove = true;
var moveX = e.touches[0].clientX;
distanceX = moveX - startX;
});
dom.addEventListener('touchend',function (e) {
/*滑动结束*/
if(isMove && Math.abs(distanceX) > 50){
if(distanceX > 0){
rightCallback && rightCallback.call(this,e);
}else{
leftCallback && leftCallback.call(this,e);
}
}
/*重置参数*/
isMove = false;
startX = 0;
distanceX = 0;
});
}
bindSwipeEvent(document.querySelector('.box'),function () {
console.log('左滑手势');
},function () {
console.log('右滑手势');
});
}
window.onload = function () {
/*使用tap事件*/
/*1. 响应的速度比click要快 150ms */
/*2. 不能滑动*/
var bindTapEvent = function (dom, callback) {
/*事件的执行顺序*/
/*在谷歌浏览器模拟看不到300ms的效果*/
/*在真机上面才能看看到延时效果*/
var startTime = 0;
var isMove = false;
dom.addEventListener('touchstart', function () {
startTime = Date.now();
});
dom.addEventListener('touchmove', function () {
isMove = true;
});
dom.addEventListener('touchend', function (e) {
console.log((Date.now() - startTime));
if ((Date.now() - startTime) < 150 && !isMove) {
callback && callback.call(this, e);
}
startTime = 0;
isMove = false;
});
bindTapEvent(document.querySelector('.box'), function (e) {
console.log(this);
console.log(e);
console.log('tap事件');
});
}
//1.下载:https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js
<script src="https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js"></script>
<script>
/*当页面的dom元素加载完成*/
document.addEventListener('DOMContentLoaded', function() {
/*初始化方法*/
FastClick.attach(document.body);
}, false);
/*正常使用click事件就可以了*/
</script>
window.onload = function () {
//最好把父容器的滑动事件的默认动作清除掉
document.querySelector('.box').addEventListener('touchmove',function(e){
e.preventDefault();
});
/*区域滚动效果*/
/*条件:一个容器装着一个容器html结构*/
/*找到父容器*/
/*子容器大于父容器*/
new IScroll(document.querySelector('.box'),{
scrollX:false,//x轴方向不能滑动
scrollY:true//Y方向可以滑动
});
}
更多的使用方法可以参考官方文档