繁体   English   中英

JavaScript无法与doctype html一起使用?

[英]JavaScript not working with doctype html?

我是HTML,CSS和JavaScript的新手,但是偶然发现了一个问题。 此代码应创建随时间推移向右移动的图片,但是仅当我删除代码的doctype行时它才起作用。 我已经在验证器中尝试了此代码,它没有显示任何错误,但是除非删除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';
然后它将同时在“标准”和“怪癖”模式下工作。

 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),但并非总是如此!

您需要提供单位,以“ px”为例:

the_image.style.left=x_position + 'px';

这是小矮人:

http://plnkr.co/edit/vyYUoItrw3S0eJyFa0wb?p=preview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM