jquery 长按
jQuery 实现长按事件的方法
在jQuery中实现长按事件可以通过结合mousedown、mouseup和setTimeout来实现。以下是具体实现方式:
基础实现
监听mousedown事件启动计时器,若在指定时间内未触发mouseup则视为长按。超过时间后执行长按回调,中途释放则清除计时器。
var pressTimer;
$(".target").on("mousedown", function() {
pressTimer = setTimeout(function() {
console.log("长按事件触发");
// 长按后的操作
}, 1000); // 1秒为长按阈值
}).on("mouseup mouseleave", function() {
clearTimeout(pressTimer);
});
移动端兼容
对于触摸设备需使用touchstart和touchend事件:
var pressTimer;
$(".target").on("touchstart", function() {
pressTimer = setTimeout(function() {
console.log("长按事件触发");
}, 1000);
}).on("touchend touchcancel", function() {
clearTimeout(pressTimer);
});
封装为插件
可扩展为jQuery插件方便复用:
$.fn.longPress = function(callback, duration) {
duration = duration || 1000;
return this.each(function() {
var timer;
$(this).on("mousedown touchstart", function() {
timer = setTimeout(callback, duration);
}).on("mouseup mouseleave touchend touchcancel", function() {
clearTimeout(timer);
});
});
};
// 使用方式
$(".btn").longPress(function() {
alert("长按成功");
}, 1500);
注意事项
- 移动端需考虑
touchcancel事件中断场景 - 长按时间阈值建议设置在500-2000ms之间
- 防止长按触发后重复执行操作
- 在拖拽场景中需要额外处理避免冲突
这种方法无需额外库,纯jQuery实现,适用于大多数需要长按交互的场景。







