jquery鼠标移入移出
jQuery鼠标移入移出事件
jQuery提供了两种常用的事件方法来处理鼠标移入和移出操作:mouseenter()/mouseleave()和hover()。以下是具体实现方式:

使用mouseenter()和mouseleave()
$("#targetElement").mouseenter(function() {
// 鼠标移入时执行的代码
$(this).css("background-color", "yellow");
});
$("#targetElement").mouseleave(function() {
// 鼠标移出时执行的代码
$(this).css("background-color", "white");
});
使用hover()方法
hover()方法可以同时处理移入和移出事件,接受两个函数参数:

$("#targetElement").hover(
function() {
// 鼠标移入时触发
$(this).addClass("highlight");
},
function() {
// 鼠标移出时触发
$(this).removeClass("highlight");
}
);
如果只需要处理移入事件,可以只传递一个函数:
$("#targetElement").hover(function() {
// 仅处理移入事件
$(this).fadeTo("fast", 0.5);
});
注意事项
mouseenter()和mouseleave()不会冒泡,而mouseover()和mouseout()会冒泡hover()内部实际使用的是mouseenter()和mouseleave()- 这些事件可以用于任何可见的DOM元素,不仅是链接或按钮
实际应用示例
// 图片悬停放大效果
$(".thumbnail").hover(
function() {
$(this).animate({width: "+=50px", height: "+=50px"}, 200);
},
function() {
$(this).animate({width: "-=50px", height: "-=50px"}, 200);
}
);
以上方法可以根据具体需求选择使用,hover()方法通常更为简洁,而分开使用mouseenter()和mouseleave()则更明确。






