如何在特定像素处停止移动图像? 对 javascript 有点陌生
一直在尝试使用 if-else,不确定我输入的代码是否正确。
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('xTank');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight()
{
if(imgObj<400){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,70); // call moveRight in 20msec
}
else
{
stopanimate = setTimeout(moveRight,70);
}
}
window.onload =init;
最佳答案
您需要检查左侧样式值,而不是图像对象本身:
function moveRight()
{
if(parseInt(imgObj.style.left, 10) < 400){
imgObj.style.left = parseInt(imgObj.style.left, 10) + 10 + 'px';
setTimeout(moveRight,70); // call moveRight in 20msec
}
else
{
//stopanimate = setTimeout(moveRight,70); // no need to animate it anymore
}
}
另外,不要忘记在某个时候调用您的 moveRight 函数。
关于javascript - 如何在特定像素处停止图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25094550/