全面阻止事件行为
- 当我们全面禁止事件默认行为的时候,在移动端
a标签是无法进行跳转的 - 在谷歌移动端模拟器中可以跳转
<a href="http://www.baidu.com">百度一下</a>
<a href="http://www.baidu.com">百度一下</a>
<a href="http://www.baidu.com">百度一下</a>
<a href="http://www.baidu.com">百度一下</a>
/* 全面禁止默认事件,真机是无法跳转的 */
document.addEventListener('touchstart',function(ev){
ev = ev||evevt
ev.preventDefault()
})
解决方案
使用BOM来解决
使用BOM中的location属性,使用步骤如下
- 获取所有的
a标签 - 遍历为
a绑定事件 - 调用
location进行跳转 - 防误触处理
// 获取所有的a标签
const aNodes = document.querySelectorAll('a')
for (let i = 0; i < aNodes.length; i++) {
// 遍历绑定监听
aNodes[i].addEventListener('touchstart',function(){
location.href = this.href
})
}
防误触
- 我们可以定义一个标识,来表示点击之后是否手指一动
- 并且使用
touchend来进行触发事件
for(var i=0;i<aNodes.length;i++){
aNodes[i].addEventListener("touchstart",function(){
this.isMoved=false;
})
aNodes[i].addEventListener("touchmove",function(){
this.isMoved=true;
})
aNodes[i].addEventListener("touchend",function(){
if(!this.isMoved){
location.href=this.href;
}
})
}
638

被折叠的 条评论
为什么被折叠?



