jquery 长按

jQuery 实现长按事件的方法
在 jQuery 中实现长按(长按触摸或鼠标按住)事件可以通过结合 mousedown、mouseup 和 setTimeout 来实现。以下是具体实现方法:

基本实现
var pressTimer;
$("#target").on('mousedown touchstart', function(e) {
// 设置定时器,延迟执行长按操作
pressTimer = setTimeout(function() {
// 长按事件的处理逻辑
console.log("长按事件触发");
}, 1000); // 设置长按时间为1000毫秒(1秒)
});
$("#target").on('mouseup touchend mouseleave', function(e) {
// 清除定时器,防止长按事件被触发
clearTimeout(pressTimer);
});
优化版本(支持触摸事件)
var pressTimer;
var longPressed = false;
$("#target").on('mousedown touchstart', function(e) {
longPressed = false;
pressTimer = setTimeout(function() {
longPressed = true;
// 长按事件的处理逻辑
console.log("长按事件触发");
}, 1000);
});
$("#target").on('mouseup touchend click', function(e) {
clearTimeout(pressTimer);
// 如果长按事件已触发,阻止点击事件
if (longPressed) {
e.preventDefault();
e.stopPropagation();
}
});
封装为 jQuery 插件
如果需要重复使用长按事件,可以将其封装为 jQuery 插件:
(function($) {
$.fn.longPress = function(fn, duration) {
var timer;
var longPressed = false;
duration = duration || 1000;
this.on('mousedown touchstart', function(e) {
longPressed = false;
timer = setTimeout(function() {
longPressed = true;
fn.call(this, e);
}, duration);
});
this.on('mouseup touchend click', function(e) {
clearTimeout(timer);
if (longPressed) {
e.preventDefault();
e.stopPropagation();
}
});
return this;
};
})(jQuery);
// 使用方式
$("#target").longPress(function() {
console.log("长按事件触发");
}, 1500); // 设置长按时间为1500毫秒
注意事项
- 在移动设备上,
touchstart和touchend事件需要与mousedown和mouseup一起绑定以确保兼容性。 - 长按时间可以根据需求调整,通常设置在 500 毫秒到 1500 毫秒之间。
- 如果长按事件触发后需要阻止后续的点击事件,可以通过
preventDefault和stopPropagation实现。
以上方法可以灵活应用于需要长按交互的场景,如长按删除、长按编辑等。






