当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Making an image stay in the new position after being moved

问题描述:

I have a JavaScript code that makes an image move horizontally for an interval of time then stop. I want the image to stay in the new position without going back to its previous place.

This is the code I have:

<script type="text/javascript">

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,20); // call moveRight in 20msec

setTimeout(stop, 350);

}

function stop(){

clearTimeout(animate);

imgObj.style.left = '0px';

}

window.onload =init;

</script>

<a href="#" onclick="moveRight();"><img id="myImage" src="book_cover.jpg"/></a>

网友答案:

var imgObj;
var elapsed = 0;

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';
    elapsed += 20;
    if (elapsed < 350) setTimeout(moveRight, 20);
}

window.onload = init;
<a href="#" onclick="moveRight()">
    <img id="myImage" src="https://placeimg.com/60/80/tech" width="60" height="80" />
</a>
分享给朋友:
您可能感兴趣的文章:
随机阅读: