[英]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
您可以使用offsetWidth
和offsetHeight
<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.