简体   繁体   English

JavaScript无法与doctype html一起使用?

[英]JavaScript not working with doctype html?

I'm new to HTML, CSS and JavaScript, and I've stumbled upon a problem. 我是HTML,CSS和JavaScript的新手,但是偶然发现了一个问题。 This code should create a picture that's moving to the right over time, but it only works if I delete the doctype line of code. 此代码应创建随时间推移向右移动的图片,但是仅当我删除代码的doctype行时它才起作用。 I've tried this code in the validator, it shows no errors, but it doesn't do what I want it to do unless I delete the doctype. 我已经在验证器中尝试了此代码,它没有显示任何错误,但是除非删除doctype,否则它不会执行我想要的操作。 What should I change here? 我应该在这里改变什么?

<!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>

In Quirks mode (without a DOCTYPE declaration), CSS sizes without units are allowed; 在Quirks模式下(没有DOCTYPE声明),允许CSS大小不带单位。 they are interpreted as pixels. 它们被解释为像素。

In Standards mode (with a DOCTYPE), CSS lengths always need units. 在“标准”模式(带有DOCTYPE)下,CSS长度始终需要单位。

So the solution is to add px to the position: the_image.style.left=x_position+'px'; 因此解决方案是将px添加到以下位置: the_image.style.left=x_position+'px';
Then it will work in both Standards and Quirks mode. 然后它将同时在“标准”和“怪癖”模式下工作。

 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"> 

As a side note, using Quirks mode is never a good idea. 附带说明,使用Quirks模式绝不是一个好主意。 In this particular case, most browsers share the same quirk (CSS size without a unit is treated as px) but that is not always the case! 在这种情况下,大多数浏览器共享相同的问题(不带单位的CSS大小被视为px),但并非总是如此!

You need to provide the unit, in your case 'px': 您需要提供单位,以“ px”为例:

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

here is the plunkr: 这是小矮人:

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

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

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