简体   繁体   English

如何获取html中根节点的实际宽度和高度?

[英]How to get the actual width and height of the root node in html?

<html>
    <head> 
        <meta charset="utf-8" /> 
        <title>test</title> 
    </head> 
    <body style="background-color: red;width: 100vw;height: 100vh" id="123">  
        <script>
            window.onresize = function() {
                var res = document.getElementsByTagName('html')[0].getBoundingClientRect();
                document.getElementById("123").innerHTML=JSON.stringify(res)
            }
        </script> 
    </body>
</html>

在此处输入图像描述 在此处输入图像描述

As in the above code, the width and height values corresponding to the window zoom will also change.如上代码,window缩放对应的宽高值也会发生变化。 The actual width and height cannot be obtained when there is a scroll bar.有滚动条时无法获取实际的宽高。 What I want to obtain is the current visible area plus the area hidden by the scroll bar, no matter how the window changes, the width and height Should be immobile我要获取的是当前可见区域加上滚动条隐藏的区域,不管window怎么变化,宽高应该是不动的

You can use offsetWidth and offsetHeight您可以使用offsetWidthoffsetHeight

 <html> <head> <meta charset="utf-8" /> <title>test</title> </head> <body style="background-color: red;width: 100vw;height: 100vh"> <div id="123"></div> <script> window.onresize = function() { document.getElementById("123").innerHTML = document.getElementsByTagName('html')[0].offsetWidth + 'x' + document.getElementsByTagName('html')[0].offsetHeight; } </script> </body> </html>

You should replace html with body .您应该将html替换为body

document.querySelector('body');

 window.onresize = function(){ document.getElementById("123").innerHTML= JSON.stringify({"width": document.body.scrollWidth, "height": document.body.scrollHeight}) }
 <html> <head> <meta charset="utf-8" /> <title>test</title> </head> <body style="background-color: red;width: auto;height: 100vh" id="123"> </body> </html>

Edit: The above code will solve your issue, use body.scrollWidth instead of clientWidth编辑:上面的代码将解决您的问题,使用body.scrollWidth而不是clientWidth

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

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