好的。也许我问过类似的问题,但这是我遇到的另一个问题。我将从展示代码开始:
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 章节。感谢大家!
我添加了一些图片,以更好地解释这一点
更新 看起来只有在动态创建 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/