简体   繁体   中英

Move div animation onmouseover,onmouseout

My code below:

JavaScript:

function showMenu(){
    var t = setInterval(move, 5);
    var menu = document.getElementById("menu");
    var pos = 0;

    function move(){
        if(pos>=150){
            clearInterval(t);
        }
        else{
            pos += 1;
            menu.style.left = pos + "px";
        }
    }

}

function hideMenu(){
    var t = setInterval(move, 10);
    var menu = document.getElementById("menu");
    var pos = menu.getAttribute("left");

    function move(){
        if(pos<=0){
            clearInterval(t);
        }
        else{
            pos -= 1;
            menu.style.left = pos + "px";
        }
    }

}

HTML:

<div id="menu-field" onmouseover="showMenu()" onmouseout="hideMenu()" >
    <div id="menu"></div>
</div>

I want the div element to move right on mouse over and start moving back to starting position on mouse out. This does the showMenu function even on mouse out.

This might be better accomplished natively with CSS and no JavaScript. This looks like it will accomplish what you're trying to do:

 #menu-field { background: #eee; height: 200px; width: 80px; } #menu { background: #aaa; height: 100px; width: 80px; transition: transform 1s; } #menu-field:hover #menu { transform: translateX(80px); } 
 <div id="menu-field"> <div id="menu">Menu</div> </div> 

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