2015-09-25 64 views
-2

我有這段代碼,只是簡單的代碼,但基本上我希望這會自動回到右側並再次循環(從右到左,在窗口的右側再次顯示在左側)現在,此代碼只讓對象無限地從左到右移動 可能嗎?如何循環這個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 
 
} 
 

 
function stop() { 
 
    clearTimeout(animate); 
 
    imgObj.style.left = '0px'; 
 
} 
 

 
window.onload = init;
<html> 
 
<head> 
 
    <title>JavaScript Animation</title> 
 
</head> 
 

 
<body> 
 
    <form> 
 
    <img id="myImage" src="/images/html.gif" /> 
 
    <p>Click the buttons below to handle animation</p> 
 
    <input type="button" value="Start" onclick="moveRight();" /> 
 
    <input type="button" value="Stop" onclick="stop();" /> 
 
    </form> 
 
</body> 
 
</html>

+1

當你的左邊的位置比你需要重置回零,使其來到左側窗口的寬度。 –

+0

如何重置和如何定義我的窗口寬度?你能舉個例子嗎? –

回答

1

如果圖像是過去寬度的窗口,它需要有它的位置復位至零。您可以使用模運算符來完成此操作。

var imgObj = null; 
 
var animate; 
 

 
function init() { 
 
    imgObj = document.getElementById('myImage'); 
 
    imgObj.style.position = 'relative'; 
 
    imgObj.style.left = '0px'; 
 
} 
 

 
function moveRight() { 
 
    var bodyWidth = document.body.clientWidth; 
 
    var newLeft = parseInt(imgObj.style.left) + 10 
 
    imgObj.style.left = newLeft % bodyWidth + 'px'; 
 
    animate = setTimeout(moveRight, 20); // call moveRight in 20msec 
 
} 
 

 
function stop() { 
 
    clearTimeout(animate); 
 
    imgObj.style.left = '0px'; 
 
} 
 

 
window.onload = init;
<html> 
 

 
<head> 
 
    <title>JavaScript Animation</title> 
 

 

 

 
</head> 
 

 
<body> 
 

 
    <form> 
 
    <img id="myImage" src="/images/html.gif" /> 
 
    <p>Click the buttons below to handle animation</p> 
 
    <input type="button" value="Start" onclick="moveRight();" /> 
 
    <input type="button" value="Stop" onclick="stop();" /> 
 
    </form> 
 

 
</body> 
 

 
</html>

+0

謝謝......它真的解決了我的問題...... –