當(dāng)鼠標(biāo)指針懸停在所選元素上時(shí),hover()方法指定兩個(gè)要運(yùn)行的函數(shù)。
此方法同時(shí)觸發(fā)mouseenter和mouseleave事件。
調(diào)用hover()方法是簡(jiǎn)寫(xiě):;$(selector).mouseenter(function_in).mouseleave(function_out)
注意:當(dāng)傳遞單個(gè)函數(shù)時(shí),hover()方法將對(duì)mouseenter和mouseleave事件都執(zhí)行該函數(shù)。
$(selector).hover(function_in, function_out)
當(dāng)鼠標(biāo)指針懸停在上方時(shí),更改所有<p>元素的背景顏色:
$("p").hover(function(){
$(this).css("background-color", "yellow");
}, function(){
$(this).css("background-color", "lightblue");
});測(cè)試看看?/?添加特殊樣式以列出要懸停的項(xiàng)目:
$(document).ready(function(){
$("li").hover(function(){funcIn(this);}, function(){funcOut(this);});
});
function funcIn(x) {
$(x).html("鼠標(biāo)<b>ENTER</b> 按下事件被觸發(fā)");
$(x).css("background", "yellow");
}
function funcOut(x) {
$(x).html("觸發(fā)鼠標(biāo)離開(kāi)事件");
$(x).css("background", "white");
}測(cè)試看看?/?如果僅指定一個(gè)函數(shù),則將同時(shí)為mouseenter和mouseleave事件運(yùn)行該函數(shù):
$("div").hover(function(){
$(this).css("background", randColor());
});
// 獲取隨機(jī)顏色函數(shù)
function randColor() {
return 'rgb(' + Math.floor(Math.random()*256) + ',' + Math.floor(Math.random()*256) +
',' + Math.floor(Math.random()*256) + ')';
}測(cè)試看看?/?| 參數(shù) | 描述 |
|---|---|
| function_in | 當(dāng)鼠標(biāo)指針進(jìn)入元素時(shí)執(zhí)行的功能 |
| function_out | (可選)當(dāng)鼠標(biāo)指針離開(kāi)元素時(shí)執(zhí)行的函數(shù) |