简体   繁体   中英

HTML5 Javascript image positioning

My question should have a simple answer, but I am very frustrated because the situation is not logical to me. What I am trying to do is put a top margin on an image on a screen. It works without a DOCTYPE line, but does not with it in place to enable HTML5.

[Good]

<html>
    <head>
        <title>HTML5 Question</title>
    </head>
    <body>
        <img src="help.jpg" id="img1" style="position:absolute">
        <script>
            document.getElementById("img1").style.top = 50;
        </script>
    </body>
</html>

[Bad]

<!DOCTYPE html>
<html>
    <head>
        <title>HTML5 Question</title>
    </head>
    <body>
        <img src="help.jpg" id="img1" style="position:absolute">
        <script>
            document.getElementById("img1").style.top = 50;
        </script>
    </body>
</html>

The good example only gives 50 pixels of top margin to the image. The only difference is the absence and existence of the first DOCTYPE line. help.jpg is a local image file. I get the same behavior for Chrome and FireFox.

向属性样式添加像素,例如

document.getElementById("img1").style.top = "50px";

You don't specify a unit. Try:

document.getElementById("img1").style.top = '50px';

Here is the correct output where the code is working.U have to use the quotes as well as units in the script.

document.getElementById("img1").style.top = "50px";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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