<!DOCTYPE html> prevents me from resizing my

2019-08-25 00:03发布

Recently I fall in love with HTML5(especially games), and I realize I should strengthen my JavaScript first, hence, I read Head First JavaScript(O'Reilly) to take a crack. I intended to display an img tag whose size is changing according to the different navigator size, but when I add !DOCTYPE html, img just cannot be resized.here is my simplified code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" /> 
        <title>Pet</title>
        <link rel="stylesheet" href="style/rock.css">
        <script type="text/javascript">
            function resizeRock(){
                document.getElementById("rock").style.height = ( document.body.clientHeight - 100 ) * 0.9;
            }
        </script>
    </head>
    <body onload="resizeRock();">
        <div id="_rock">
            <img src="image/rock.png" alt="Rock" id="rock"/>
        </div>
    </body>
</html>

If I remove !DOCTYPE html, everything goes well, but I'd like to know the reason, what's more, I'd like to know how to resize img tag in HTML5. Thanks!

2条回答
Anthone
2楼-- · 2019-08-25 00:28

When you add <!DOCTYPE html>, you put the document into standards mode.

There's a couple of changes you need to make to get this working. First, in standards mode, the page is only as high as it needs to be. So document.body.clientHeight is just the height of your image and a little bit of margin. To make the height of the page match that of the viewport, as happens by default in quirks mode add this CSS:

html, body { height:100% }

Second, in standards mode, you need to state the dimensions you're using when setting style.width and style.height. This is as easy as adding + "px" to the end of the size setting line, making it

document.getElementById("rock").style.height = 
                                    ( document.body.clientHeight - 100 ) * 0.9 + "px";
查看更多
一夜七次
3楼-- · 2019-08-25 00:30

Most likely <img> is being inline CSS element and you cannot set height for such elements.

Add:

 #rock {
       display: block;
 }

in your stylesheet.

Moer info

查看更多
登录 后发表回答