2016-06-15 158 views
0

獲取錯誤,說明遞歸過多。實際上必須移動圖像。即使我試圖清除超時,它也會給出相同的錯誤。image.style.left無法正常工作javascript

注:我發現the_image.style.left沒有移動圖像。

<!DOCTYPE HTML> 
<html> 
<head> 
<style> 
.image_style{left:x} 
</style> 
<script> 
var the_timer, x_position = 0, my_image; 
function move_image(){ 
     my_image = document.getElementById("imag"); 
     x_position = x_position+1; 
     my_image.style.left = x_position; 
     the_timer = setTimeout(move_image(), 200); 
} 
</script> 
</head> 
<body onclick="move_image()"> 
<img src = "desert.jpg" id = "imag" 
     style="position:obsolute; width:300px; height:400px; left:0"> 
     <script> 
       my_image = document.getElementById("imag"); 
       alert(my_image.style.left); 
     </script> 
</body> 
</html> 
+3

'position:obsolute;'to'position:absolute;'。 – choz

+0

你有一個錯字。它的'絕對'不'絕對' –

+0

它似乎工作https://fiddle.jshell.net/attp1qcx/ my_image.style.left是0px像它應該是 – Roysh

回答

0

您需要致電setInterval而不是setTimeOut。現在你正在函數中調用函數,這是一個永無止境的過程,這就是爲什麼你會遇到錯誤。

另請參見left屬性需要px中的值,而您僅指定一個不會移動圖像的數字。

setInterval(function() { move_image() }, '1000'); 

function move_image() { 

     my_image = document.getElementById("imag"); 
     x_position = x_position + 1; 
     my_image.style.left = x_position + "px"; 
     console.log(x_position); 

    }