【问题标题】:Drop Down menu -- onmouseout getting invoked on the child node when set in the parent node下拉菜单——在父节点中设置时在子节点上调用 onmouseout
【发布时间】:2012-02-09 15:54:00
【问题描述】:

试图模仿以下链接中的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>

【问题讨论】:

    标签: javascript onmouseover onmouseout


    【解决方案1】:

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

    您可以在 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;
    

    【讨论】:

    • 更改了代码,但是当鼠标移动到项目(即内容)时 - onmouseout 被触发 - 目标是 container 本身,尽管鼠标在容器本身内。 !!
    • 通过链接thefutureoftheweb.com/blog/bursting-the-event-bubble 他说——如果你把鼠标移到一个孩子身上,这会触发父母的 mouseout 事件。在这种情况下,目标将匹配父级 - 所以,您提供的答案不起作用,并试图弄清楚为什么会这样..
    • @Vivek:当然可以。抱歉,我设法完全弄错了,并让你大打出手。我已将答案更改为更正确。
    • 这是一个窗口对象,不是吗?
    • @Vivek:如果您根据更新后的答案将onmouseout="unfire(... 更改为onmouseout="unfire.call(...,则this 应该是“容器”对象。您可能需要使用代码,仍然检查event.target || event.srcElement 以避免冒泡问题。注意,如果您通过 JavaScript 附加处理程序,则处理事件会容易得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多