300ms,主要发生在mobile
- 为啥会出现300ms延迟现象
- 浏览器想知道用户是否dobule tap(双击缩放)
- 下列情况不会出现300ms延迟
- 桌面浏览器
- meta的viewport设置了
user-scalable=no
(禁止缩放) - meta的viewport设置了
width
或者initial-scale
- IE11+,设置了
touch-action: manipulation;
.For IE10 use-ms-touch-action: manipulation;
移动端点透
发生情况:
- A,B两个层上下重叠在Z轴中
- 绑定
touchstart/touchend
事件,使上层的A点击后消失 - B默认有click事件或B绑定了click事件
为什么会产生点透:
- 移动端事件执行顺序:
touchstart -> touchend -> click
解决方案:
- 尽量用touch事件替换click事件
- 阻止a标签的click的情况:在消失元素的
touchstart/touchend
事件,调用event.preventDefault
或者event.returnValue = false
- A和B都用
click
事件做绑定 - fastclick原理(在body中绑定监听事件,然后做出判断,是否需要调用preventDefault来处理)
以下为demo,跑一遍就能懂大概原理
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- wipe 300ms delay -->
<!-- Instead of above code, your can see div2 has 300ms delay -->
<meta name="viewport" content="user-scalable=no, initial-scale=1.0">
<style>
*{
margin: 0px;
padding:0px;
}
#div1{
300px;
height: 300px;
background-color: rgba(255,0,0,0.25);
}
#div2{
240px;
height: 240px;
background-color: yellow;
position: absolute;
left: 30px;
top: 30px;
z-index: -1;
}
#console{
border: 1px solid green;
position: absolute;
top: 300px;
100%;
}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2">
<a href="http://www.baidu.com">jump to baidu.com</a>
</div>
<div id="console"></div>
<script>
$ = function (id) {return document.getElementById(id)}
var div1 = $("div1");
var div2 = $('div2');
var con = $('console');
var sDate, eDate;
function handle(e){
// computed time interval
if (sDate == null) {
sDate = (new Date).getTime()
}
eDate = (new Date).getTime()
var tar = e.target,
eve = e.type;
// prevent 点透
if(eve == "touchend") {
console.log(tar)
e.preventDefault();
}
var ele = document.createElement("p");
ele.innerHTML = "target:"+ tar.id + " event:" + eve + ' interval: ' + (eDate-sDate) + 's';
con.appendChild(ele);
if(tar.id === "div1"){
div1.style.display = "none";
}
}
div1.addEventListener("touchend",handle);
div1.addEventListener("touchstart",handle);
div2.addEventListener("click",handle);
</script>
</body>
</html>