简体   繁体   中英

Resetting position based on style.right

I was trying to reset animation when the image reaches right-most edge of the screen.

Everything works perfectly fine without this line:

if (imgObj.style.right == 0) {
    Reset();
}

Is it not the right way?

 <!-- var imgObj = null; var animate; function init() { imgObj = document.getElementById('myImage'); imgObj.style.position = 'relative'; imgObj.style.left = '0px'; } function moveRight() { imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px'; animate = setTimeout(moveRight, 2000); // call moveRight in 20msec if (imgObj.style.right == 0) { Reset(); } } function Reset() { clearTimeout(animate); imgObj.style.left = '0px'; } window.onload = init; //--> 
 <form> <img id="myImage" src="http://jsfiddle.net/img/logo.png" /> <p>Click the buttons below to handle animation</p> <input type="button" value="Start" onclick="moveRight();" /> <input type="button" value="Reset" onclick="reset();" /> </form> 

How to get the animation working along with that above line ?

You have some mistakes

  1. onclick="Reset();" not onclick="reset();"

  2. parseInt(imgObj.style.left.replace("px","")) not parseInt(imgObj.style.left)

  3. imgObj.style.right is always "" you have to set some thing like imgObj.style.left.replace("px","")>200

 var imgObj = null; var animate; function init() { imgObj = document.getElementById('myImage'); imgObj.style.position = 'relative'; imgObj.style.left = '0px'; } function moveRight() { imgObj.style.left = parseInt(imgObj.style.left.replace("px","")) + 10 + 'px'; animate = setTimeout(moveRight, 2000); // call moveRight in 20msec if (parseInt(imgObj.style.left.replace("px",""))+ imgObj.width>= window.innerWidth) { Reset(); } } function Reset(){ clearTimeout(animate); imgObj.style.left = '0px'; } window.onload = init; 
 <form> <img id="myImage" src="http://jsfiddle.net/img/logo.png" /> <p>Click the buttons below to handle animation</p> <input type="button" value="Start" onclick="moveRight();" /> <input type="button" value="Reset" onclick="Reset();return false;" /> </form> 

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