最近我开始在 javascript 中玩触摸事件,我遇到了一个关于 touchend 事件的奇怪问题(可能是一些显而易见的事情,我太笨了,无法理解)。所以基本上,这是我的代码:
function send(e) {
e.preventDefault();
document.body.innerHTML = e.type + "<br>" + e.targetTouches[0].pageY;
}
['touchstart', 'touchmove', 'touchend'].forEach(function(e) {
window.addEventListener(e, send, false);
});
Run Code Online (Sandbox Code Playgroud)
现在e.targetTouches[0].pageY工作正常,但e.type将只假定 touchstart 或 touchmove 值,而不是出于某种原因的 touchend。我注意到只有当我尝试在同一行中调用e.type属性或从 event.targetTouches(或 event.touches)数组读取任何属性后才会发生这种情况。这些属性不是只读的吗?为什么它会阻止我的代码?
哦,在玩了几个小时后,我注意到 event.type 只会在将一根手指放在屏幕上然后用另一根手指点击时才会假定 touchend 值,但这仍然不能解决我的问题。
这是因为在移除触摸点时会触发 touchend 事件。
没有接触点,没有目标接触。
一个TouchList列出所有触摸物体的接触点是仍与触摸表面接触
MDN触端
所述touchend当事件被触发的触摸点从触摸表面移除
为了解决您的问题,在 touchstart 和 touchmove 时记录 targetTouches,并在移除触摸点时使用它:
var TargetTouches;
function send(e) {
e.preventDefault();
var type = e.type;
var pageY;
if (type !== 'touchend') {
pageY = e.targetTouches[0].pageY;
TargetTouches = e.targetTouches[0];
} else {
pageY = TargetTouches.pageY;
}
document.body.innerHTML = type + "<br>" + pageY;
}
['touchstart', 'touchmove', 'touchend'].forEach(function(e) {
window.addEventListener(e, send, false);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1965 次 |
| 最近记录: |