2015-10-18 90 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

相关问题