How to apply event.stopPropagation?
Let me explain the problem first. I am using the following UL structure:
<ul onmouseover="smenu_over(this)" onmouseout="smenu_out(this)" class="sub-menu" style="left:0;">
<li><a href="#">Navigation Item with long text do text wrap</a></li>
<li><a href="#">Sub nav item</a></li>
<li><a href="#">Sub nav item</a></li>
<li style="border-bott开发者_运维百科om:0;"><a href="#">Sub nav item</a></li>
</ul>
JS Function
function smenu_over(obj) {
var a = obj.parentNode.childNodes[0];
if(a!=null) {
var top = $(".topnav_icons").length && !$(".logo_t").length ? "-45px" : "-34px";
setBckPosition(a, top);
a.style.color = "#fff";
}
}
I need to apply the event.stopPropagation
inside this function which is called when mouseover
event happen.
Please help me the code to apply event.stopPropagation
?
You mean this:
$('ul.sub-menu a').mouseenter(function(event){
event.stopPropagation();
// your code....
});
You can remove your current handlers from being in-line, like this:
<ul class="sub-menu" style="left:0;">
Then you can bind these functions in jQuery, like this:
$(function() { //run when DOM is ready
$("ul.sub-menu").hover(smenu_over, smenu_out);
});
In your functions, instead of obj
just use this
, it'll refer to the element you're hovering, like this:
function smenu_over() {
var a = this.parentNode.childNodes[0];
if(a!=null) {
var top = $(".topnav_icons").length && !$(".logo_t").length ? "-45px" : "-34px";
setBckPosition(a, top);
a.style.color = "#fff";
}
}
The important difference here is .hover()
maps to the mouseenter
and mouseleave
events (not mouseover
/mouseout
), which don't fire on the parent when entering/leaving a child, so no need to stop propagation, they already behave like you want.
You can probably optimize this much further, but without seeing your other code I don't want to give you any bad advice, this will fix the current issue though.
精彩评论