适配
移动端事件
事件类型
移动端事件列表
- touchstart 元素上触摸开始时触发
- touchmove 元素上触摸移动时触发
- touchend 手指从元素上离开时触发
- touchcancel 触摸被打断时触发
这几个事件最早出现于 IOS safari 中,为了向开发人员转达一些特殊的信息。
应用场景
touchstart 事件可用于元素触摸的交互,比如页面跳转,标签页切换
touchmove 事件可用于页面的滑动特效,网页游戏,画板
touchend 事件主要跟 touchmove 事件结合使用
touchcancel 使用率不高
注意:
- touchmove 事件触发后,即使手指离开了元素,touchmove 事件也会持续触发
- 触发 touchmove 与 touchend 事件,一定要先触发 touchstart
- 事件的作用在于实现移动端的界面交互
事件绑定
方式一
box.ontouchstart = function () {
console.log('touch start')
}
方式二
box.addEventListener('touchstart', function () {
console.log('touch start')
})
这里推荐使用第二种,第一种有时会失灵。
点击穿透
touch 事件结束后会默认触发元素的 click 事件,如没有设置完美视口,则事件触发的时间间隔为 300ms 左右,如设置完美视口则时间间隔为 50ms 左右。
如果 touch 事件隐藏了元素,则 click 动作将作用到新的元素上,触发新元素的 click 事件或页面跳转,此现象称为点击穿透
解决方法
- 阻止当前元素事件的默认行为。
cls.addEventListener('touchstart', function (e) {
e = e || event
e.preventDefault()
})
问题:将来有很多元素要一个一个写,代码太多了
- 阻止所有元素事件的默认行为。
document.addEventListener('touchstart', function (e) {
e = e || event
e.preventDefault()
})
问题:因为禁止了所有元素默认行为,导致 a 标签不能跳转链接了
- 给 a 标签添加跳转链接的方式
var allA = document.querySelectorAll('a')
for (let i = 0; i < allA.length; i++) {
const a = allA[i]
a.addEventListener('touchend', function () {
window.location.href = this.href
})
}
问题:a 标签有误触
- 解决误触
var allA = document.querySelectorAll('a')
for (let i = 0; i < allA.length; i++) {
const a = allA[i]
a.addEventListener('touchmove', function () {
this.isMove = true
})
a.addEventListener('touchend', function () {
if (this.isMove) return
window.location.href = this.href
})
}
fastclick
一个专门用于解决事件点透的库
仓库地址:https://github.com/ftlabs/fastclick