I programmed an img element to "fall" down the window with parseInt(its.style.top) triggered by a setInterval(fall,1000) function in the body.
An error occurs after the Moves() function is triggered, and the fall() function stops being called. Is there an if-statement for Moves() function to call the setInterval(fall,1000) again after the img s.style.left >= r.style.width??
Thanks! :-)
<html>
<body onload="setInterval(fall,1000)" onkeydown="Moves()">
<img id="square" style="position:absolute; left:10px; top:0px;
width:50px; height:50px; background-color:red;" />
<img id="rectangle" style="position:absolute; left:10px; top:130px;
width:150px; height:10px; background-color:blue;" />
<script>
function fall(){
var s = document.getElementById("square");
s.style.top = parseInt(s.style.top) + 25 + 'px';
var r = document.getElementById("rectangle");
r.style.top=130 + 'px';
if(s.style.top>=r.style.top){s.style.top=r.style.top;}
}
function Moves(){
var s = document.getElementById("square");
if (event.keyCode==39) {
s.style.left = parseInt(s.style.left)+10+'px';}
var r = document.getElementById("rectangle");
r.style.width=150 + 'px';
if(s.style.left>=r.style.width){setInterval(fall,1000);}
}
</script>
</body> </html>
function fall
works, if you don't try toMove
? Usually, you use something likeElement.getBoundingClientRect()
to gettop
andleft
properties, asstyle
properties are unable to be retrieved on many a Browser. – StackSlave