问题
Trying to mimic the browse catagories
in the following link https://dev.twitter.com/discussions
onmouseover
-- the container expands to fit the new items within itself -- but,moving the mouse within the container(expanded conainer) will result in the onmouseout
getting invoked -- even when the mouse is within the container itself -- silly mistake or not trying hard to find out where and how i might be going wrong
Code --
<html>
<style type="text/css">
#container{
overflow: hidden;
height: auto;
width: 350px;
background-color: rgba(0,0,0,0.65);
}
.contents{
height: 30px;
width: 350px;
background-color: yellow;
float: left;
}
</style>
<script type="text/javascript" >
var foo = new Array("bar","santa","claus")
function fire(){
var contents = document.getElementById("contents")
if(contents.hasChildNodes())
return
for(i = 0 ; i < foo.length ; i++){
var tem=document.createElement("div");
tem.setAttribute("id",'cont'+i);
tem.setAttribute("class","contents");
tem.appendChild(document.createTextNode(foo[i]))
contents.appendChild(tem)
}
}
function unfire(evt){
if ((evt.target || evt.srcElement).id != "container")
return;
var contents = document.getElementById("contents");
while(contents.hasChildNodes())
contents.removeChild(contents.firstChild)
}
</script>
<div id="container" onmouseover="fire(event)" onmouseout="unfire(event)">
Move your mouse here
<div id="contents" ></div>
</div>
</html>
回答1:
Sorry, I got my original answer completely wrong, I'm not sure what I was thinking. Of course, mouseout
fires on a parent when the mouse moves to a child. In this case, you need to check the relatedTarget
or toElement
properties of the event
object and check to see if that element is a descendant of the container.
You can check ancestry using contains()
in Internet Explorer and compareDocumentPosition()
in other browsers. For example, change onmouseout="unfire(event)"
to onmouseout="unfire.call(this, event)"
and add the following code to the unfire
function:
var to = evt.relatedTarget || evt.toElement;
if((this.contains && this.contains(to)) || this.compareDocumentPosition(to) & 16)
return;
来源:https://stackoverflow.com/questions/8850673/drop-down-menu-onmouseout-getting-invoked-on-the-child-node-when-set-in-the-p