jq 给一个div设置长按2秒函数
以下是一个基本的长按2秒函数,可以应用于div元素:
let timer;
function longPress() {
timer = setTimeout(() => {
// 在这里编写长按2秒后要执行的代码
console.log("长按2秒!");
}, 2000);
}
function clearTimer() {
clearTimeout(timer);
}
const div = document.querySelector("div");
div.addEventListener("mousedown", longPress);
div.addEventListener("mouseup", clearTimer);
div.addEventListener("touchstart", longPress);
div.addEventListener("touchend", clearTimer);
这个函数使用了setTimeout()和clearTimeout()来模拟长按2秒的效果。当鼠标或触摸按下时,longPress()函数会启动一个2秒的计时器。如果在这2秒内鼠标或触摸抬起,计时器会被清除,长按事件不会被触发。如果计时器完成了2秒,就会执行预设的代码。
原文地址: https://www.cveoy.top/t/topic/b6vz 著作权归作者所有。请勿转载和采集!