如何检测长按按钮/图像
How to detect a long press on a button/image
我正在做一个phonegap项目。我需要进行一次长时间的新闻发布会。如何使用JavaScript检测长按图像/按钮?
$('#target').mousedown(function() {
alert('Handler for .mousedown() called.');
//start a timer
});
$('#target').mouseup(function() {
alert('Handler for .mouseup() called.');
//stop the timer and decide on long click
});
我想到的一种方法是:
-
在onclick事件开始时,记录时间,这将为您提供第一次单击的时间。
-
然后检查时间跨度。假设,你说5秒的时间跨度是一个长按事件。如果检查成功,则这是一个长按事件。
正面解决方案:
const btn = document.querySelector("button");
const info = document.querySelector("h3");
let time;
btn.onmousedown = () => {
time = new Date(Date.now()).getSeconds();
setTimeout(() => {
let timecurrent = new Date(Date.now()).getSeconds();
if (timecurrent - time == 5) {
info.innerText = "yes pressed";
time = undefined;
}
}, 5000);
}
btn.onmouseup = () => {
time = undefined;
info.innerText = "no pressed";
}
<button>press me</button>
<h3>No pressed</h3>
功能解决方案:
function catchLongPress(element, delay) {
const elem = document.querySelector(element);
let time;
elem.onmousedown = () => {
time = new Date(Date.now()).getSeconds();
setTimeout(() => {
let timecurrent = new Date(Date.now()).getSeconds();
if (timecurrent - time == delay) {
alert("yes pressed");
time = undefined;
}
}, delay * 1000);
}
elem.onmouseup = () => {
time = undefined;
alert("no pressed");
}
}
catchLongPress("button", 2);
<button>press me</button>
<h3>No pressed</h3>
相关文章:
- 如何使按钮图像在单击时添加到变量中
- HTML滚动按钮图像:如何使用Internet Explorer
- jquery ui按钮图像没有更改
- 如何检测长按按钮/图像
- 使用 Jquery 的单选按钮图像
- 如何在 jqgrid 中添加新的按钮/图像列
- Javascript,切换具有相同名称的单选按钮图像
- 我怎样才能使这个切换的javascript按钮(图像)不那么笨拙
- w2ui-单击时工具栏更改按钮图像
- Jquery在ajax上设置onclick null并更改按钮图像成功
- 如何更改HTML5音频中的播放/按钮图像
- 日期选择器按钮图像未显示
- jQuery是否验证冲突提交函数,而不是表单按钮(图像/超链接)
- 我需要添加一个图像数组,可以使用JavaScript更改按钮图像或数字条目
- 在firefox中创建自定义按钮(使用自定义按钮插件)不允许我调整按钮图像的大小
- 更改按钮图像onclick
- Angular JS知道什么是用复选框图像和单选按钮图像触发的
- 用按钮图像填充表单文本字段
- javascript表单提交更改提交按钮图像
- 从内联css和JavaScript点击更改按钮图像