问题
I have a html structure like :
<div onmouseover="enable_dropdown(1);" onmouseout="disable_dropdown(1);">
My Groups <a href="#">(view all)</a>
<ul>
<li><strong>Group Name 1</strong></li>
<li><strong>Longer Group Name 2</strong></li>
<li><strong>Longer Group Name 3</strong></li>
</ul>
<hr />
Featured Groups <a href="#">(view all)</a>
<ul>
<li><strong>Group Name 1</strong></li>
<li><strong>Longer Group Name 2</strong></li>
<li><strong>Longer Group Name 3</strong></li>
</ul>
</div>
I want the onmouseout event to be triggered only from the main div, not the 'a' or 'ul' or 'li' tags within the div!
My onmouseout function is as follows :
function disable_dropdown(d)
{
document.getElementById(d).style.visibility = "hidden";
}
Can someone please tell me how I can stop the event from bubbling up? I tried the solutions (stopPropogation etc) provided on other sites, but I'm not sure how to implement them in this context.
Any help will be appreciated.
Thanks a lot!
回答1:
The events that you really want to use are onmouseenter and onmouseleave, however they are not implemented in all browsers. You could look to implement them yourself, however you would in this case be better off using a library that has already solved the problem cross browser for you. So, in jQuery
<div id="main">
My Groups <a href="#">(view all)</a>
<ul>
<li><strong>Group Name 1</strong></li>
<li><strong>Longer Group Name 2</strong></li>
<li><strong>Longer Group Name 3</strong></li>
</ul>
<hr />
Featured Groups <a href="#">(view all)</a>
<ul>
<li><strong>Group Name 1</strong></li>
<li><strong>Longer Group Name 2</strong></li>
<li><strong>Longer Group Name 3</strong></li>
</ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$('#main').hover(function() { enable_dropdown(1); }, // mouseenter
function() { disable_dropdown(1); }); // mouseleave
</script>
来源:https://stackoverflow.com/questions/2632764/stop-event-bubbling-in-javascript