首页 > 解决方案 > 如何检测何时在 js 中按住按钮?

问题描述

我试图检测一个按钮何时被手指按住一段未指定的时间。但是我不知道该怎么做。

我尝试这样做,就像在线示例显示的那样

const b = document.getElementById("hold-me");

b.onclick = function() {
  setTimeout(alert, 2000, "you held me down for 2 second");
}
<body>
<button id="hold-me">Hold me</button>
</body>

但是,它不符合我想要做的事情,因为我希望只要按下按钮就能够触发事件。

编辑:

为了补充一点,设置超时功能在这里,因为它大致就是我在网上找到的示例所做的。这是示例:https ://codepen.io/thetallweeks/pen/uAEGr?editors=0010

我在网上找到的示例没有帮助,因为我想查询是否连续按下按钮以了解我是否应该移动我的遥控车。

标签: javascriptdom

解决方案


第一个变体,在“未指定时间”后触发事件;

const b = document.getElementById("hold-me");
let time;
b.onpointerdown = function() {
  time = Date.now();
}
b.onpointerup = function() {
  console.log(`you held me down for ${Date.now() - time} milliseconds`);
}
<body>
<button id="hold-me">Hold me</button>
</body>

第二个变体,在“未指定的时间”内触发事件:

const b = document.getElementById("hold-me");
let timer;
b.onpointerdown = function() {
  timer = setTimeout(alert, 2000, "you held me down for 2 second");
}
b.onpointerup = function() {
  clearTimeout(timer);
}
<body>
<button id="hold-me">Hold me</button>
</body>


推荐阅读