下拉菜单-在父节点中设置时,在子节点上调用onmouseout

Drop Down menu -- onmouseout getting invoked on the child node when set in the parent node

本文关键字:子节点 调用 onmouseout 设置 父节点 下拉菜单      更新时间:2023-09-26

尝试在以下链接中模拟browse catagorieshttps://dev.twitter.com/discussions

onmouseover——容器扩展以适应容器中的新项目——但是,在容器中移动鼠标(扩展的容器)将导致onmouseout被调用——即使鼠标在容器中——愚蠢的错误或没有努力找出哪里以及如何出错

代码——

<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>

对不起,我原来的答案完全错了,我不确定我在想什么。当然,当鼠标移动到子对象时,mouseout会在父对象上激发。在这种情况下,您需要检查event对象的relatedTargettoElement属性,并检查该元素是否是容器的后代。

您可以在Internet Explorer中使用contains(),在其他浏览器中使用compareDocumentPosition()来检查祖先。例如,将onmouseout="unfire(event)"更改为onmouseout="unfire.call(this, event)",并在unfire函数中添加以下代码:

var to = evt.relatedTarget || evt.toElement;
if((this.contains && this.contains(to)) || this.compareDocumentPosition(to) & 16)
    return;