jquery鼠标移入事件
jQuery鼠标移入事件的基本用法
使用.hover()方法或.mouseenter()方法可以绑定鼠标移入事件。以下是两种方法的示例:
// 方法1:使用.hover(),包含移入和移出两个回调函数
$("#element").hover(
function() {
// 鼠标移入时执行的代码
$(this).css("background-color", "yellow");
},
function() {
// 鼠标移出时执行的代码(可选)
$(this).css("background-color", "");
}
);
// 方法2:仅使用.mouseenter()绑定移入事件
$("#element").mouseenter(function() {
$(this).css("font-weight", "bold");
});
事件委托的用法
对于动态生成的元素,需要使用事件委托:

$(document).on("mouseenter", ".dynamic-element", function() {
$(this).addClass("highlight");
});
结合CSS过渡效果
可以在事件中触发CSS动画:

$(".box").mouseenter(function() {
$(this).stop().animate({
width: "200px",
opacity: 0.8
}, 300);
});
防止事件冒泡
需要阻止事件冒泡时:
$(".inner-element").mouseenter(function(e) {
e.stopPropagation();
// 其他处理代码
});
获取事件相关信息
可以从事件对象中获取相关信息:
$(".item").mouseenter(function(e) {
console.log("鼠标位置:", e.pageX, e.pageY);
console.log("目标元素:", e.target);
});
注意事项
.hover()是.mouseenter()和.mouseleave()的简写形式- 鼠标移入事件会冒泡,需要注意事件委托层级
- 对于频繁触发的事件,建议使用防抖或节流技术
- 移动设备上没有鼠标事件,需要考虑触摸事件替代方案






