我有一个JavaScript代码,可以使图像水平移动一段时间然后停止。我希望图像保持在新的位置,而不会回到以前的位置。
这是我的代码:
<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>
答案 0 :(得分:0)
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>