移动端在touch上一共有4个事件javascript
这里会结合click对上面的事件进行讨论, touch发生在click以前css
先上段代码,直观感觉一下html
<!DOCTYPE html> <html> <head> <style type="text/css"> #level0 { /* width: 500px; height: 500px; */ } #level1-0 { background: red; width: 500px; height: 500px; } #level1-1 { background: green; width: 500px; height: 500px; } </style> </head> <body> <div id="level0"> <div id="level1-0"> </div> <div id="level1-1"> </div> </div> </body> <script type="text/javascript"> var level10 = document.getElementById("level1-0"); level10.addEventListener('touchstart', function(e) { console.log(1); }); level10.addEventListener('touchmove', function(e) { console.log(2); }); level10.addEventListener('touchend', function(e) { console.log(3); }); level10.onclick = function() { console.log(5); } document.body.onclick = function() { console.log('6'); } </script> </html>
level10.addEventListener('touchstart', function(e) { console.log(1); e.preventDefault(); });
点击的时候 发现 只有 1 3, 说明click被阻止了,固然在touchend里面加效果也同样,因此 在touch事件里面加 e.preventDefault能够取消系统产生的click事件, 固然不会阻止后面的touch事件。java
产生点透问题的缘由, 能够先看看代码吧浏览器
<!DOCTYPE html> <html> <head> <style type="text/css"> #level0 { /* width: 500px; height: 500px; */ position: relative; } #level1-0 { position: absolute; z-index: 1; background: red; width: 500px; height: 500px; } #level1-1 { background: green; width: 500px; height: 500px; } </style> </head> <body> <div id="level0"> <div id="level1-0"> </div> <div id="level1-1"> </div> </div> </body> <script type="text/javascript"> var level10 = document.getElementById("level1-0"); var level11 = document.getElementById("level1-1"); level10.addEventListener('touchstart', function(e) { level10.style.display = 'none'; }); level11.onclick = function() { console.log('level11莫名被点击了'); } </script </html>
level11莫名被点击了
, 这就是点透
当手指触摸到屏幕的时候,系统生成两个事件,一个是touch 一个是click,touch先执行,touch执行完成后,A从文档树上面消失了,并且因为移动端click还有延迟200-300ms的关系,当系统要触发click的时候,发如今用户点击的位置上面,目前离用户最近的元素是B,因此就直接把click事件做用在B元素上面了
.
level10.addEventListener('touchend', function(e) {
e.preventDefault();
});
固然点透问题,还有其余的解决方法,关键是 要么是需求本次系统生成的click事件,要么是当系统触发click的时候,当前的触发touch的那个dom节点还存在。好比将其一延迟3s在关闭dom
setTimeout(() => { level10.style.display = 'none'; }, 300);