此文为本人原创,如若雷同,纯属巧合!欢迎转载,转载请注明出处,谢谢!
遇到的问题及测试
在项目过程中,封装touch事件时,发现了touch事件与mouse等事件的一些区别,且touch事件在某情况下不会触发touchend,上测试代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
#div{
width: 400px;
height: 400px;
background-color: red;
}
#divchild{
width: 200px;
height: 200px;
background-color: blue;
}
</style>
</head>
<body onselectstart ="return false;" onmousedown="return false;" oncontextmenu= "return false;">
<div id='div'><div id='divchild'></div></div>
<script>
window.onload = function(){
var div = document.getElementById('div');
var child = document.getElementById('divchild');
div.addEventListener('touchstart',function(e){
setTimeout(function(){
child.remove();
},1000);
console.log('触发了touchstart');
console.log(e.target);
});
div.addEventListener('touchend',function(e){
console.log('触发了touchend');
console.log(e.target);
});
}
</script>
</body>
</html>
测试浏览器:chrome56;
1.测试方式:首先点击蓝色区域并保持长按,待蓝色区域消失时停止长按,会发现touchend事件并没有触发;
2.刷新,按照步骤1的方式点击红色区域,触发touchend事件;
3.将Demo中touchestart touchend分别替换为mousedown及mouseup,再进行步骤1 2,在移动端模式和非移动端模式(不知道该不该这样称呼,见谅)mouse事件有着不一样的结果,非手机模式下两个事件都正常触发,但移动端模式下,mouseup事件长按始终不会触发(短按会触发,未使用安卓系统测试),此行为让我感觉很怪异,个人判断可能与移动端click事件300ms延迟有关系;
touch测试结果
touch测试结果
mouse测试结果
mouse测试结果
关于touch事件行为的测试结果:
从测试可以看出,在demo中,若touchend触发前将e.target元素删除,将终止touch后续事件(touchmove touchend)的触发(原因应该是target被删除无法捕获或冒泡到监听元素),可得出touchstart touchmove touchend三个事件为联动事件(自己起的名字),这三个事件(或许还有一个touchcancel)共用一个target,即在事件触发前并不会重新获取target,沿用上一个事件的target;而在非移动端的mousedown及mouseup事件为独立事件(自己起得名字)–应该会在触发前重新获取target,而在移动端测试下行为个人认为颇为怪异,想不明白,只是认为可能和click的300ms延迟有关系。
由于本人才疏学浅,若存在错误欢迎批评指正,在此不胜感激!