gpt4 book ai didi

javascript - window.clientWidth 在 IE 中始终为 0

转载 作者:行者123 更新时间:2023-11-29 22:20:34 26 4
gpt4 key购买 nike

我需要 IE 中包含文档的窗口的实际像素 clientWidth 以计算适当的缩放值,但发现窗口始终返回值 0。有没有办法从任何 DOM 对象获取此值?我是 JS 新手,发现只要缩放比例为 100%,document.body.clientWidth 就可以解决问题,否则会返回缩放后的像素值。帮忙?

最佳答案

在 Internet Explorer 8 之前的版本中,它以物理像素大小检索宽度,而从版本 8 开始,它以逻辑像素大小返回宽度。

这是什么意思?

如果浏览器未处于正常缩放级别(用户可以放大或缩小网页:CTRL 和 +、CTRL 和 -),则 clientWidth 属性在版本 8 中的工作方式与早期版本不同。

  • 在 Internet Explorer 8 之前的版本中,即使文档中的当前像素大小不同,宽度也会以默认像素大小计算。
  • 在 Internet Explorer 8 和 Firefox、Opera、Google Chrome 和 Safari 中,宽度以当前像素大小计算。

例如,如果缩放级别为 200%,对于相同的客户端窗口大小,clientWidth 属性在版本 8 之前检索的值是版本 8 的两倍。

获取浏览器窗口大小的跨浏览器解决方案:

<head>
<script type="text/javascript">
// always return 1, except at non-default zoom levels in IE before version 8
function GetZoomFactor() {
var factor = 1;
if (document.body.getBoundingClientRect) {
// rect is only in physical pixel size in IE before version 8
var rect = document.body.getBoundingClientRect();
var physicalW = rect.right - rect.left;
var logicalW = document.body.offsetWidth;
// the zoom level is always an integer percent value
factor = Math.round((physicalW / logicalW) * 100) / 100;
}
return factor;
}

function GetWindowSize() {
var zoomFactor = GetZoomFactor();
var w = Math.round(document.documentElement.clientWidth / zoomFactor);
var h = Math.round(document.documentElement.clientHeight / zoomFactor);
var info = document.getElementById("info");
info.innerHTML = w + "px * " + h + "px";
}
</script>
</head>
<body onload="GetWindowSize ()">Size of the browser's client area:
<span id="info" style="margin-left:20px;"></span>

<div
style="width:500px; height:1000px; background-color:#e0a0a0;">Size of this element: 500px * 1000px</div>
</body>

关于javascript - window.clientWidth 在 IE 中始终为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12684007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com