jquery鼠标事件
jQuery 鼠标事件基础
jQuery 提供了丰富的鼠标事件处理方法,用于响应用户的鼠标操作。常见事件包括点击、悬停、移动等。以下是一些核心鼠标事件及其用法:
click()
绑定单击事件,当元素被点击时触发。
$("#element").click(function() {
alert("元素被点击");
});
dblclick()
双击事件,元素被快速点击两次时触发。
$("#element").dblclick(function() {
$(this).hide();
});
鼠标悬停与移出
hover()
结合鼠标进入和离开事件,接受两个函数参数。
$("#element").hover(
function() { // 鼠标进入
$(this).css("background", "yellow");
},
function() { // 鼠标离开
$(this).css("background", "");
}
);
mouseenter() 和 mouseleave()
单独处理鼠标进入和离开,无事件冒泡。

$("#element").mouseenter(function() {
$(this).addClass("highlight");
}).mouseleave(function() {
$(this).removeClass("highlight");
});
鼠标移动与坐标获取
mousemove()
跟踪鼠标在元素内的移动,常用于获取坐标。
$("#element").mousemove(function(e) {
$("#log").text("X: " + e.pageX + ", Y: " + e.pageY);
});
mousedown() 和 mouseup()
分别处理鼠标按键按下和释放事件。
$("#element").mousedown(function() {
console.log("按键按下");
}).mouseup(function() {
console.log("按键释放");
});
事件对象与高级用法
通过事件对象 event 可以获取更多交互细节:

$("#element").click(function(e) {
console.log("触发元素: " + e.target.id);
console.log("按键代码: " + e.which); // 1-左键, 2-中键, 3-右键
});
使用 on() 动态绑定事件:
$(document).on("click", ".dynamic-element", function() {
alert("动态元素被点击");
});
实际应用示例
实现拖拽功能:
let isDragging = false;
$("#draggable").mousedown(function() {
isDragging = true;
});
$(document).mousemove(function(e) {
if (isDragging) {
$("#draggable").css({
left: e.pageX,
top: e.pageY
});
}
}).mouseup(function() {
isDragging = false;
});
注意事项:
- 使用
off()解绑事件避免内存泄漏 - 移动端需结合触摸事件(如
touchstart) - 事件委托(通过
on()绑定父元素)适合动态内容






