简体   繁体   中英

Whats wrong with my JavaScript animation?

So i have this web-page to design and i want an image of the moon to rise-up from bottom of the screen to top. This is the HTML :

<body>
    <div id="Moon" onload="Moon()"></div>
</body>

CSS :

#Moon{
    width: 150px;
    height: 150px;
    left: 50px;
    top: 600px;
    background: transparent url(../Img/Moon.SVG) no-repeat ;
    position: absolute;
}

and JavaScript for animation :

function Moon(){
    var Moon=document.getElementById("Moon");
    var yposition=Moon.style.top;
    var id = setInterval(frame, 10);
    function frame(){
        if (Moon.style.top > 100) {
          yposition--; 
          Moon.style.top = yposition + 'px'; 
        } else {
          clearInterval(id);
        } 
        frame();
    }
}

but for some reasons the image of moon stays at the bottom of the page and doesn't move at all. any ideas?

Try like this.

you need to calculate top offset of the div using moon.offsetTop and a div does not have a onload event so you will have to call your Moon() function either from script or from body onload event

 function Moon(){ var moon=document.getElementById("Moon"); var yposition= parseInt(moon.offsetTop) ; var id = setInterval(frame, 10); function frame() { if (moon.offsetTop > 10) { yposition--; document.getElementById("Moon").style.top = yposition + 'px'; } else { clearInterval(id); } } } 
 #Moon{ width: 300px; height: 250px; left: 50px; top: 600px; background: transparent url("https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQh7mGmBMJ--wS711QkCEPHHS56jV15VmESttDbVLZPSI_FsMAyTQ") no-repeat ; position: absolute; } 
 <body onload="Moon()"> <div id="Moon"></div> </body> 

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