我是 HTML、CSS 和 JavaScript 的新手,我偶然发现了一个问题。这段代码应该创建一个随着时间的推移向右移动的图片,但它只有在我删除 doctype 代码行时才有效。我已经在验证器中尝试过这段代码,它没有显示任何错误,但是除非我删除文档类型,否则它不会执行我希望它执行的操作。我应该在这里更改什么?
<!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>
最佳答案
在 Quirks 模式下(没有 DOCTYPE 声明),允许没有单位的 CSS 大小;它们被解释为像素。
在标准模式下(使用 DOCTYPE),CSS 长度总是需要单位。
所以解决办法是在位置上加上px
:the_image.style.left=x_position+'px';
然后它将在 Standards 和 Quirks 模式下工作。
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">
附带说明一下,使用 Quirks 模式从来都不是一个好主意。在这种特殊情况下,大多数浏览器都有相同的怪癖(没有单位的 CSS 大小被视为 px),但情况并非总是如此!
关于JavaScript 不能使用 doctype html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33202945/