简体   繁体   中英

javascript triggers “onmouseover” and “onmouseout” when i hover the div in another div

I am working on a grid layout for my new website. The PHP code:

echo"<div class='model_container_invisible' onMouseOver='fade(this, 0)' onMouseOut='fade(this, 1)'>";
            echo"<span class='model_title_wrapper'>";
                echo"<span class='model_title'>Ancient Dragon</span>";
                echo"<span class='model_designer'>designed by Kamiya Satoshi</span>";
            echo"</span>";
            echo"<img class='model_img' src='img/models/001.jpg' />";
echo"</div>";

this is for on grid element. the opacity of the image is 0.5, i want to change it when i hover the element with my js function fade(). here is its code:

function fade(elem, direction)
{
/* if(elem.className == "model_container_invisible")
    elem.className = "model_container_visible";
else
    elem.className = "model_container_invisible"; */

var img = elem.getElementsByTagName("img")[0]; //das Bild

if(direction == 0) //einblenden
{
    alert("fadein, this: "+elem);
    img.style.opacity = 0.5;

    var aktiv = window.setInterval(function() {
        img.style.opacity = String(Number(img.style.opacity) + .05);
        if(Number(img.style.opacity) >= 1.0) {
            window.clearInterval(aktiv);    

        }
    }, 8);
}
else //ausblenden
{
    alert("fadeout, this: "+elem);
    img.style.opacity = 1;

    var aktiv = window.setInterval(function() {
        img.style.opacity = String(Number(img.style.opacity) - .05);
        if(Number(img.style.opacity) <= 0.5) {
            window.clearInterval(aktiv);    

        }
    }, 16);
}
}

but when my mouse pointer moves from on div into another div (lets say from model_title_wrapper to model_titel), the function is called again. i dont get it!

can you please help me? thanks!

Use onmouseenter instead of onmouseover as the later will fire the event when hovering in child elements, while onmouseenter will not (the event will not bubble up).

See info about the onmouseenter/onmouseleave events that you should use:

http://www.quirksmode.org/js/events_mouse.html#mouseenter

This happens because of default JavaScript event bubbling concept. When some event occurs on an element (like in this case the model_title ) the event bubbles up to the parent document element.

Since the parent div ( model_container_invisible ) has one event handler, it will be executed irrespective of where exactly inside the event has actually occurred.

So to avoid this issue, you should verify if the eventSource is actually model_container_invisible and perform required logic.

Following link might help you : http://www.javascripter.net/faq/eventtargetsrcelement.htm

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