2013-02-19 87 views
0

我使用JQuery mouseenter事件來顯示另一個div內的div。當鼠標進入DIV A時,它會顯示一個較小的DIV B.問題是,當我將鼠標放在DIV B上時,JQuery再次運行mouseenter事件。我想顯示DIV B(內部一個),當鼠標移過它時,不要再次觸發mouseenter事件。雖然在技術上,我的鼠標仍然懸停DIV A.所以換句話說,在DIV B上的Mouseout導致JQuery再次在DIV A上運行mouseenter,這是我所理解的。JQuery mouseenter在重疊div上多次觸發

enter image description here

代碼:

$(document).on("mouseenter", ".si", function (e) { 
    settingsIcon(e,1); 

}); 

$() 

$(document).on("mouseout", ".si", function (e) { 
    settingsIcon(e,0); 

}); 

function settingsIcon(e, action) { 

if (action === 1) // show 
{ 
    $(".settings_icon").remove(); 
    var id = parseInt(e.target.id.replace("dvci_", ""), 10); 
    $("#dvc_" + id).prepend("<div class='settings_icon' ><img class='settings_icon_image' src='settings.png' style='width:59px; height:57px' /></div>"); 
    var icon = $("#dvc_" + id + " .settings_icon"); 

    icon.css({ 
     "left": ($("#dvci_" + id).width()/2) - 30, 
     "top": parseInt($("#dvci_" + id).css("margin-top").replace("px", ""), 10) + ($("#dvci_" + id).height()/2) - 30 
    }); 

    $(".settings_icon img").show("scale", {}, 400); 

} 
else { 
    // hide 
    $(".settings_icon").remove(); 
} 
} 

的jsfiddlehttp://jsfiddle.net/tLUrd/

+0

發佈您的jQuery代碼。並看看event.stopPropagation(); – ryadavilli 2013-02-19 12:51:36

+0

我按照您的要求添加了代碼 – 2013-02-19 13:01:51

回答

1

試試這個使用event.stopPropagation()

$(document).on("mouseenter", ".si", function (e) { 
    settingsIcon(e,1); 
}); 

$(document).on("mouseleave", ".si", function (e) { 
    settingsIcon(e,0); 
}); 

$(document).on("mouseenter", "#b", function (e) { 
    e.stopPropagation(); 
}); 

$(document).on("mouseleave", "#b", function (e) { 
    e.stopPropagation(); 
}); 
+0

我已將代碼添加到問題中。我試過你顯示的內容,但似乎不起作用。 – 2013-02-19 13:04:10

+0

更新了代碼,嘗試一次... – 2013-02-19 13:10:31

+0

試過了,它沒有工作:(當我把鼠標放在DIV B上時,它隱藏了它,它不應該,只有當我離開DIV A時 – 2013-02-19 13:23:41

-1

jQuery的.hover()佔用了兩個帕ameters:

$("#a").hover(
    function() { settingsIcon(null, 1); }, 
    function() { settingsIcon(null, 0); } 
); 

編輯:

爲了避免重新綁定上述事件,如果你動態地生成#A:

$(document).on({ 
    mouseenter: function() { settingsIcon(null, 1); }, 
    mouseleave: function() { settingsIcon(null, 0); } 
}, '#a'); 
+0

當然,你可以殺死settingsIcon – Zac 2013-02-19 14:01:08

+0

的第一個參數動態添加Divs,所以它不會工作,任何方式來改變上述代碼匹配動態添加的元素,所以我可以檢查?。謝謝 – 2013-02-19 14:11:21

+0

回答更新! – Zac 2013-02-19 14:31:46

0
$("selector").hover(
    function() { 
    console.log("mouse in"); 
    }, 
    function() { 
    console.log("mouse out"); 
    } 
); 

http://api.jquery.com/hover/

jQuery.hover()不會爲兒童元素開火,只爲e lement它是必然的,從而解決你的問題。我之前也有過這樣的幾次,.hover()真的能做到這一點。

+0

您能否提供代碼示例。內部div是動態生成的。我確實使用了鼠標而不是mouseenter,但它導致了同樣的問題(懸停:函數(e){settingsIcon(e,1);},)。問題在於mouseleave函數。當我在DIV B上時,它會觸發DIV A的mouseleave – 2013-02-19 15:37:26