简体   繁体   中英

JavaScript DOM parent/child relation on mouse event

OK Maybe I have asked something similar to this, but this is another problem I have. I will start by showing the code:

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);
            }
        }
    }
}

So, this is just about a simple image appearing when I move the mouse over a div , then disappears when I move the mouse out. Yet, this is not behaving as I want.

The problem is that when, while the mouse is over the parent div , if I move it over the child img (still over the parent), the MouseOut() function is fired.

I have been searching for solutions and tricks all these days but everything was in vain. Now, I hope somebody can identify the problem. There must be some JavaScript chapter that I missed out. Thanks to everybody!

I added some images, to explain this better

情况1情况二情况3案例4

UPDATES Looks like this happens only when the IMG child is created dinamically. If I create it before and only change it's src, it works.

JSSFIDLE DEMO You can see this script working (well, not working, better said) at http://jsfiddle.net/E9q6e/1/

You can try to check, if Parent contains the child in MouseOut() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM