2014-03-04 34 views
0

我想動畫化圖像以在頁面上滾動。我目前有一個這樣的onClick版本,但希望它自動運行在頁面加載。從onclick變爲onload

伊夫試圖在body標籤中添加的onload = 'MoveRight的()',但我得到一個錯誤:

'無法讀取的屬性類型 'NULL''

的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) + 1 + 'px'; 
     animate = setTimeout(moveRight,400); // call moveRight in 400msec 
    } 
    function stop(){ 
     clearTimeout(animate); 
     imgObj.style.left = '0px'; 
    } 
    window.onload =init; 
    //--> 
</script> 

HTML

<html> 

    <head> 

    <title>JavaScript</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

添加另一個函數來調用initmoveRight上onload.Modify您的代碼如下所示:

<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) + 1 + 'px'; 
     animate = setTimeout(moveRight, 400); // call moveRight in 400msec 
    } 
    function stop() { 
     clearTimeout(animate); 
     imgObj.style.left = '0px'; 
    } 
    function InitMove() { 
     init(); 
     moveRight(); 
    } 
    window.onload = InitMove; 

</script> 
+0

完美,謝謝:)。 爲什麼不讓我添加'window.onload = moveRight;'到代碼的結尾?理論上,這要求代碼執行與您的功能相同的操作。 – Gary