简体   繁体   English

我的JavaScript动画怎么了?

[英]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 : 这是HTML:

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

CSS : CSS:

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

and JavaScript for animation : 和JavaScript动画:

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 您需要使用moon.offsetTop计算div的顶部偏移,并且div没有onload事件,因此您必须从脚本或body onload事件中调用Moon()函数

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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