jQuery的hover()方法用于在鼠标悬停在一个或多个元素上时触发事件。
使用方法如下:
- 绑定hover事件:
$(selector).hover(handlerIn, handlerOut);
其中,selector是要绑定事件的元素选择器,handlerIn是鼠标进入元素时要触发的函数,handlerOut是鼠标离开元素时要触发的函数。
- 直接传递一个函数:
$(selector).hover(handler);
这种情况下,handler函数将在鼠标进入和离开元素时都会触发。
- 使用mouseenter和mouseleave事件:
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
这种方式与hover()方法的第一种方式效果相同。
示例:
// 当鼠标进入元素时,改变元素的背景颜色 $(".box").hover(function() { $(this).css("background-color", "red"); }, function() { $(this).css("background-color", "blue"); }); // 鼠标进入和离开元素时,显示和隐藏一个提示框 $(".tooltip").hover(function() { $(this).find(".tooltip-text").show(); }, function() { $(this).find(".tooltip-text").hide(); });
以上示例中,当鼠标进入.box元素时,将其背景颜色改为红色,当鼠标离开时,将其背景颜色改为蓝色。当鼠标进入.tooltip元素时,显示.tooltip-text元素,当鼠标离开时,隐藏.tooltip-text元素。