当触摸被取消时,如何让处理程序运行? (例如,我可以取消突出显示按钮当 CSS 不能帮我做这件事时 https://stackoverflow.com/questions/74843213/chrome-mobile-javascript-events-corresponding-to-css-active-state-changes#)。在旧版 Chrome Mobile 浏览器中,我可以捕捉到touchcancel
事件。但是,在 Chrome Mobile 108(从 2022 年起)中,没有touchcancel
:
当触摸(以及随后的click
事件)因超时而取消? (注意:将触摸移离元素是2011年的单独问题 https://stackoverflow.com/questions/5748476/ with a 不错的填充材料 https://stackoverflow.com/a/5748761/5896591.)
我正在使用以下脚本来捕获事件:
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<style>
html, body, pre {
position:absolute; top:0; left:0; right:0; bottom:0;
margin: 0; user-select: none;
}
pre {margin: 10px; overflow-y:auto}
</style>
</head>
<body>
<pre id="ELEM"></pre>
<script>
ELEM = document.getElementById("ELEM")
ELEM.appendChild(document.createTextNode(""));
function Print(s)
{
let t = (new Date() / 1000 % 60).toFixed(2).padStart(5,0);
ELEM.firstChild.nodeValue += `${t}: ${s}\n`;
ELEM.scrollTop = ELEM.scrollHeight;
}
Print("Hello, world!");
EVENTS = ["mouseup", "mousedown", "touchstart", "touchend", "click", "touchcancel", "mouseenter", "mouseout", "focusin"];
for (let e of EVENTS)
document.body.addEventListener(e, () => {Print(e)});
</script>
</body>
</html>
我真的非常希望有一种方法可以解决这个问题而无需重写click
。然而,否则(或同时)这是一种可能的方法:
- 应用程序忽略内置的
click
事件(因为我们无法捕获它的超时)。
- On
touchstart
, start a timeout (what time value should I use?).
- 如果超时触发,则生成正常的
touchcancel
event.
- On
touchend
,如果超时尚未触发,则向应用程序生成单击事件并清除超时。
这是一个例子Better_Click()
使用上述方法启动的函数touchcancel
and better-click
应用程序的事件:
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<style>
html, body, pre {
position:absolute; top:0; left:0; right:0; bottom:0;
margin: 0; user-select: none;
}
pre {margin: 10px; overflow-y:auto}
</style>
</head>
<body>
<pre id="ELEM"></pre>
<script>
ELEM = document.getElementById("ELEM")
ELEM.appendChild(document.createTextNode(""));
function Print(s)
{
let t = (new Date() / 1000 % 60).toFixed(2).padStart(5,0);
ELEM.firstChild.nodeValue += `${t}: ${s}\n`;
ELEM.scrollTop = ELEM.scrollHeight;
}
function Better_Click(el)
{
let to;
function timeout()
{
to = undefined;
el.dispatchEvent(new CustomEvent("touchcancel", {}));
}
el.addEventListener('touchstart', () => to = setTimeout(timeout, 700));
el.addEventListener('touchend', () => {
if (to === undefined)
return;
clearTimeout(to);
to = undefined;
el.dispatchEvent(new CustomEvent("better-click", {}));
});
}
Better_Click(document.body);
Print("Hello, world!");
EVENTS = ["mouseup", "mousedown", "touchstart", "touchend", "touchcancel", "mouseenter", "mouseout", "better-click"];
for (let e of EVENTS)
document.body.addEventListener(e, () => Print(e));
</script>
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)