最近在做一些移动端页面,需要对触摸事件进行监听处理。在PC上用chrome模拟手机开发了第一个版本后并测试完成后,再在手机上进行最后的真机测试。结果是,程序对触摸事件的监听处理在苹果手机上表现正常,而在安卓平台上则出现部分手机表示异常。实际调试结果表明,出现异常的原因在于,这部分安卓手机上的touchend监听事件不触发。
首先我是找寻网上别人的经验,果然在知乎上有个问答有关于这个问题的讨论。具体原因是:
On Android ICS if no preventDefault is called on touchstart or the first touchmove, further touchmove events and the touchend will not be fired.As a workaround we need to decide in the first touchmove if this is a scroll (so we don’t call preventDefault) and then manually trigger touchend.
我的解决方法是:
在touchstart的handle中使用event.preventDefault(), 即可让touchend事件正常触发
上述方法虽然可以回避touchend不触发的bug,但也使得监听元素上的click事件无法被监听处理。我的解决方式是在touchend里对用户的动作进行分类,把点击事件分类出来,并进行另外处理。
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#touchArea {
height: 300px;
background-color: #eee;
line-height: 300px;
text-align: center;
font-size: 3rem;
}
</style>
</head>
<body>
<div id="touchArea">滑动我来吧!</div>
<script type="text/javascript">
var touchArea = document.getElementById('touchArea');
var startX, endX, resX;
var touchstart = function (e) {
startX = e.changedTouches[0].clientX;
e.preventDefault(); // 解决某些安卓客户端上touchend不触发bug
};
var touchend = function (e) {
endX = e.changedTouches[0].clientX;
resX = endX - startX;
if (resX > 0) {
// 向右滑动
console.log('向右滑动');
} else if (resX < 0) {
// 向左滑动
console.log('向左滑动');
} else {
// 点击
console.log('点击');
}
};
touchArea.addEventListener('touchstart', touchstart);
touchArea.addEventListener('touchend', touchend);
</script>
</body>
</html>
注:在移动端浏览器运行或PC用浏览器模拟手机端
感谢您的阅读!
如果看完后有任何疑问,欢迎拍砖。
欢迎转载,转载请注明出处:http://www.yangrunwei.com/a/14.html
邮箱:glowrypauky@gmail.com
QQ: 892413924