一、click在手机上的延迟问题(300ms左右)
1. 加上视口
width=device-width 解决苹果
user-scalable = no 解决安卓
<meta name="viewport" content="width=device-width, initial-scale=1.0 , user-scalable = no">
2. 使用fastclick.js
去BootCDN下载一下fastClick.js,然后在js里写上FastClick.attach(document.body);
<script src="./js/fastclick.js"></script>
<script>
FastClick.attach(document.body);
</script>
3. 使用zepto.js 中的tap事件
使用的时候载入zepto.js和touch.js
<script src="./js/zepto.js"></script>
<script src="./js/touch.js"></script>
<script>
window.onload = function () {
$("div").on("tap",function(){
//这里写点击事件要执行的代码
})
}
</script>
注:在这里我想说明一下事件的执行顺序是:touchstart > touchend > click
示例:
<body>
<div class="box" style="width: 200px;height: 200px;background-color: #ccc;"></div>
<script>
var oBox = document.querySelector(".box")
oBox.addEventListener("click",function(){
console.log("click")
})
oBox.addEventListener("touchstart",function(){
console.log("touchstart")
})
oBox.addEventListener("touchmove",function(){
console.log("touchmove")
})
oBox.addEventListener("touchend",function(){
console.log("touchend")
})
</script>
</body>
最终的结果如图:
二、移动端的点透问题
点透问题的发生原因是,在点击的时候上面层消失的太快,导致下面的元素也会被点击,其解决方案有:
1. fastclick.js
2. 使用viewport
3. zepto
以上三种方法的使用前面已经说过,就不再重复。
4. 绑定相同的事件
//使用这种方法点击div这个遮罩层的时候就不会触发h元素的alert事件
var oDiv = document.querySelector("div")
var h = document.querySelector("h1")
oDiv.addEventListener("touchstart",function(){
this.style.display = "none"
})
h.addEventListener("touchstart",function(){
alert("h1")
})