如何检测长按按钮/图像

How to detect a long press on a button/image

本文关键字:按钮 图像 何检测 检测      更新时间:2023-09-26

我正在做一个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
});

我想到的一种方法是:

  1. 在onclick事件开始时,记录时间,这将为您提供第一次单击的时间。

  2. 然后检查时间跨度。假设,你说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>