2015-10-18 57 views
2

我是新來的HTML,CSS和JavaScript,我偶然發現了一個問題。這段代碼應該創建一個隨着時間的推移向右移動的圖片,但只有當我刪除doctype代碼行時才能使用。我在驗證器中試過這段代碼,它沒有顯示任何錯誤,但是它沒有做我想做的事情,除非我刪除了文檔類型。我應該在這裏改變什麼?JavaScript不能與doctype html一起使用?

<!doctype html> 
<html> 
    <head> 
     <title>Timer pomeranje</title> 
     <script> 
      var the_timer, x_position = 0, the_image; 
      function set_timer() { 
       the_image = document.getElementById("djuro_image"); 
       x_position = x_position + 1; 
       the_image.style.left=x_position; 
       the_timer = setTimeout(set_timer, 50); 
      } 
     </script> 
    </head> 
    <body onload = "set_timer()"> 
     <img src = "Djuro.png" id = "djuro_image" style = "position:absolute; left:0px" alt = "Djuro"> 
    </body> 
</html> 
+0

你不應該寫你的JavaScript在你的腦袋 – gr3g

+0

你」必須告訴你正在使用哪個瀏覽器。 – JJJ

回答

6

在怪癖模式(沒有DOCTYPE聲明)中,允許沒有單位的CSS尺寸;它們被解釋爲像素。

在標準模式下(使用DOCTYPE),CSS長度始終需要單位。

因此,解決方案是增加px的位置:the_image.style.left=x_position+'px';
然後,它會在這兩個標準和怪癖模式工作。

var the_timer, x_position = 0, the_image; 
 

 
function set_timer() { 
 
    the_image = document.getElementById("djuro_image"); 
 
    x_position = x_position + 1; 
 
    the_image.style.left = x_position + 'px'; 
 
    the_timer = setTimeout(set_timer, 50); 
 
} 
 

 
set_timer();
<img src="Djuro.png" id="djuro_image" style="position:absolute; left:0px" alt="Djuro">

作爲一個側面說明,使用怪癖模式從來都不是一個好主意。在這種特殊情況下,大多數瀏覽器共享相同的怪癖(不帶單位的CSS尺寸被視爲px),但情況並非總是如此!

+0

非常感謝您的解釋,它現在的作品:) – Bokeh

相關問題