gpt4 book ai didi

javascript - 在台式机和移动设备上检测点击(或触摸)的最可靠方法是什么?

转载 作者:行者123 更新时间:2023-11-30 11:09:26 24 4
gpt4 key购买 nike

我正在订阅 button 元素上的 click 事件。如果你点击按钮,这似乎在移动设备上有效,但如果你按住它一会儿然后松开,它就不会触发。至少在我最近使用 Chrome 的 Android 手机上是这样的。

所以我想在按钮释放时触发一些东西。因此,我假设我不应该选择 touchstart,因为它会在第一次按下按钮时触发。

  • 我需要订阅多个事件吗?哪些?
  • 如果我订阅多个事件,是否需要preventDefault()

我找到了这篇文章,但它是 2013 年的文章:https://www.html5rocks.com/en/mobile/touchandmouse/

最佳答案

所以我按照自己的方式进行了尝试,它似乎工作正常。它也会在鼠标单击、短按和长按时触发。由于问题是关于 Chrome 的,所以我在 Android 上的 Chrome 71.0.3578.99 上进行了测试。

首先,您需要禁止用户选择按钮,否则不会执行长按。

其次,为什么每个人都如此关心在其他地方释放鼠标/手指?开始单击/点击然后移动/滑开的唯一原因是用户改变了主意,不想执行按钮所说的任何操作。

最后,在我的代码中,我根据需要删除和添加事件监听器。这只是因为问题结构:此代码适用于桌面和移动设备。它也不会在支持鼠标和触摸屏的设备上中断。

用要点回答问题:

  • 是的,至少同时有两个 - clicktouchstart/touchend
  • 是的,您需要它来防止短按时的双重触发(如果您从我的代码中删除它,您会看到在短按时它会触发 touchend 然后 click事件)。您可能更愿意假设如果触发一次触摸事件,则用户没有鼠标连接到设备 - 在这种情况下,只需删除 clickFunc() 的全部内容,除了 //您的代码:它将正常工作。

const button = document.getElementById("button");
function clickFunc(e){
if(e.touches){
e.preventDefault(); //Try to comment it out: double triggers on short tap
button.removeEventListener("touchend", clickFunc);
button.addEventListener("click", clickFunc);
console.log('tapped!');
}else{
console.log('clicked!');
}
//
//Your code here
}
function touchFunc(){
button.removeEventListener("click", clickFunc);
button.addEventListener("touchend", clickFunc);
}
window.onload=function(){
button.addEventListener("click", clickFunc);
button.addEventListener("touchstart", touchFunc);
}
#button{
user-select: none; /*find crossbrowser solution!*/

/*For testing purposes*/
margin-top: 100px;
margin-left: 100px;
font-size: 48px;
padding: 10px 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Clicks and Touches</title>
</head>
<body>
<button id="button">Click me!</button>
</body>
</html>

关于javascript - 在台式机和移动设备上检测点击(或触摸)的最可靠方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54337994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com