此文为本人原创,如若雷同,纯属巧合!欢迎转载,转载请注明出处,谢谢!
遇到的问题及测试
测试方法如下
在项目过程中,封装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;
color: #FFF;
}
#divconsole{
height: 400px;
width: 100%;
background-color: #000;
color: #FFF;
}
</style>
</head>
<body ontouchstart = "return false;"> <!-- ontouchstart屏蔽弹出菜单,消除可能的菜单影响原因 -->
<div id='div'>
<div id='divchild'>长按测试</div>
</div>
<br /><br /><br />
<div id='divconsole'>显示结果:<br /></div>
<script>
function divconsole(str){
var text = document.createTextNode(str);
document.getElementById('divconsole').appendChild(text);
}
window.onload = function(){
var div = document.getElementById('div');
var child = document.getElementById('divchild');
div.addEventListener('touchstart',function(e){
setTimeout(function(){
child.remove();
},500);
divconsole('触发了touchstart...');
});
div.addEventListener('touchend',function(e){
divconsole('触发了touchend...');
});
}
</script>
</body>
</html>
测试浏览器:chrome56;
1.测试方式:首先点击蓝色区域并保持长按,待蓝色区域消失时停止长按,会发现touchend事件并没有触发;
2.刷新,按照步骤1的方式点击红色区域,触发touchend事件;
3.将Demo中touchestart touchend分别替换为mousedown及mouseup,再进行步骤1 2,在移动端模式和非移动端模式(不知道该不该这样称呼,见谅)mouse事件有着不一样的结果,非手机模式下两个事件都正常触发,但移动端模式下,mouseup事件长按始终不会触发(短按会触发,未使用安卓系统测试),此行为让我感觉很怪异,个人判断可能与移动端click事件300ms延迟有关系;
#关于touch事件行为的测试结果: 从测试可以看出,在demo中,若touchend触发前将e.target元素删除,将终止touch后续事件(touchmove touchend)的触发(原因应该是target被删除无法捕获或冒泡到监听元素),可得出touchstart touchmove touchend三个事件为联动事件(自己起的名字),这三个事件(或许还有一个touchcancel)共用一个target,即在事件触发前并不会重新获取target,沿用上一个事件的target;而在非移动端的mousedown及mouseup事件为独立事件(自己起得名字)--应该会在触发前重新获取target,而在移动端测试下行为个人认为颇为怪异,想不明白,只是认为可能和click的300ms延迟有关系。
由于本人才疏学浅,若存在错误欢迎批评指正,在此不胜感激!
本文探讨了touch事件与mouse事件的区别,特别是在移动端环境下。通过实际测试案例,展示了touch事件在特定条件下的触发机制,包括touchend事件在目标元素被移除时的失效情况。
161

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



