javascript - 如何检测何时在 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
我在网上找到的示例没有帮助,因为我想查询是否连续按下按钮以了解我是否应该移动我的遥控车。
解决方案
第一个变体,在“未指定时间”后触发事件;
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>
推荐阅读
- python - TypeError: __init__() 得到了一个意外的关键字参数“大小”
- node.js - 当对象名称之一是数字时,如何获取从 API 获取的 JSON 文件中的数据
- node.js - 在 Bot Framework 如何使用 node.js 从自适应卡片 [图像和选择] 返回选定的值
- python - OR-Tools 具有多次行程、多次接送和有限容量的车辆路线
- docker - “Install-PackageProvider ContainerImage -Force”在 Windows Server 2016 中引发错误
- sql - 将字符串列转换为字符行
- python - 如果帖子包含“好”字,则排除帖子
- python - 创建新环境并从 Anaconda 命令提示符 (Windows) 安装 Notebook 后,Jupyter Notebook 不起作用
- python-3.x - 计算 gcp 监控中无数据持续时间超过 1 天
- java - Jackson @JsonAnySetter 在与 Jackson ObjectMapper treeToValue 方法一起使用时忽略重复键的值