製作懸停下拉效果時,hover() 與 live() 是兩種常見寫法,差別在於是否能作用於動態加入的元素。下面用同一個產品目錄的效果來示範。
// live 主要用於對動態加載出來的元素綁定事件
$(".lm_div_q dd").live({
mouseenter: function() {
$(this).find("strong").addClass("tj_strong");
$(this).find("strong").next().slideDown(200); // 顯示下拉框
},
mouseleave: function() {
$(this).find("strong").removeClass("tj_strong");
$(this).find("strong").next().slideUp(200); // 隱藏下拉框
}
});
$(".lm_div_q dd").hover(function(){
$(this).find("strong").addClass("tj_strong");
$(this).find("strong").next().stop(true,true).slideDown(200); // 顯示下拉框
}, function(){
$(this).find("strong").removeClass("tj_strong");
$(this).find("strong").next().stop(true,true).slideUp(200); // 隱藏下拉框
});
兩者都能完成滑入顯示、滑出隱藏的下拉效果。差別在於:live() 綁定的事件對之後動態產生的元素也有效,適合內容會透過 Ajax 動態載入的情況;hover() 則是對當前已存在的元素直接綁定。另外 hover 版本搭配了 stop(true,true),可避免連續快速滑動時動畫堆疊。依據元素是否會動態新增,選擇合適的寫法即可。