鼠标事件上的 JavaScript DOM 父/子关系

标签 javascript dom mouseover mouseout

好的。也许我问过类似的问题,但这是我遇到的另一个问题。我将从展示代码开始:

var MyClass = {
    // Set up the events for the parent
    // MyParent is a DIV
    SetEvents: function() {
         MyParent.onmouseover = function() { MyClass.MouseHover(MyParent); };
         MyParent.onmouseout = function() { MyClass.MouseOut(MyParent); };
    },

    // Function activated when moving the mouse over the parent
    MouseHover: function(Parent) {
        if (Parent) {
        // Here I create the child, when moving the mouse over the parent control
        // The child is an IMG
            var child = document.createElement("img");
                child.id = "child";
                child.src = "child.png";
                child.style.float = "right";
            Parent.appendChild(child);
        }
    },

    // Function activated when moving the mouse out of the parent control
    MouseOut: function(Parent) {
        if (Parent) {
            var child = document.getElementById("child");
            if (child) {
                // On mouse out I remove the child
                Parent.removeChild(child);
            }
        }
    }
}

所以,这只是一个简单的图像,当我将鼠标移到 div 上时出现,然后当我将鼠标移出时消失。然而,这并不像我想要的那样。

问题是当鼠标在父 div 上时,如果我将它移到子 img 上(仍在父级上),MouseOut() 函数被触发。

这些天我一直在寻找解决方案和技巧,但一切都是徒劳的。现在,我希望有人能找出问题所在。一定有一些我错过的 JavaScript 章节。感谢大家!

我添加了一些图片,以更好地解释这一点

Case 1 Case 2 Case 3 Case 4

更新 看起来只有在动态创建 IMG 子项时才会发生这种情况。如果我之前创建它并且只更改它的 src,它就可以工作。

JSSFIDLE 演示 你可以在 http://jsfiddle.net/E9q6e/1/ 看到这个脚本在工作(好吧,不工作,更好的说法)

最佳答案

您可以尝试检查 Parent 是否包含 MouseOut() 中的 child:

var ref=event.toElement || event.relatedTarget; // This line is pseudocode
if(!Parent.contains(ref)){
  Parent.removeChild(child);
}

关于鼠标事件上的 JavaScript DOM 父/子关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10650994/

相关文章:

javascript - 将递归函数转换为异步 CPS 实现 (javascript)

javascript - 通过隐藏或删除元素来优化移动网络应用程序?

html - 无法将图像放入适当的容器中。图像堆叠,div 乱序?

javascript - 服务器端按钮单击事件未在 UpdatePanel 内触发

javascript - jQuery:粘性导航栏更改边距

javascript - 错误 : Property 'modalStack' does not exist on type 'NgxSmartModalService' . 您的意思是 '_modalStack' 吗?

html - css 或 xpath 选择器 : elements which have any attribute with specific value

html - gnuplot 4.7 超文本不适用于 Canvas 终端

matlab - 如何在 Matlab 图形中添加工具提示或叠加文本

javascript - 在 PHP 中,我从 mySQL 编码了一个 JSON 数组。我想在不同的 php 文件中解码它