我正在尝试编写一个 JavaScript 函数来获取当前浏览器的宽度。
我找到了这个:
console.log(document.body.offsetWidth);
但它的问题是,如果主体的宽度为 100%,它就会失败。
还有其他更好的功能或解决方法吗?
我正在尝试编写一个 JavaScript 函数来获取当前浏览器的宽度。
我找到了这个:
console.log(document.body.offsetWidth);
但它的问题是,如果主体的宽度为 100%,它就会失败。
还有其他更好的功能或解决方法吗?
我最初的答案是在 2009 年写的。虽然它仍然有效,但我想在 2017 年更新它。浏览器的行为仍然会有所不同。我相信 jQuery 团队在保持跨浏览器一致性方面做得很好。但是,没有必要包含整个库。在 jQuery 源代码中,相关部分可以在维度.js 的第 37 行找到。在这里它被提取并修改为独立工作:
function getWidth() {
return Math.max(
document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth
);
}
function getHeight() {
return Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight,
document.documentElement.clientHeight
);
}
console.log('Width: ' + getWidth() );
console.log('Height: ' + getHeight() );
由于所有浏览器的行为都不同,您需要先测试值,然后使用正确的值。这是一个为您执行此操作的函数:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
if (document.body) {
return document.body.clientWidth;
}
}
和高度类似:
function getHeight() {
if (self.innerHeight) {
return self.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
if (document.body) {
return document.body.clientHeight;
}
}
使用getWidth()或在脚本中调用这两个getHeight()。如果没有定义浏览器的本机属性,它将返回undefined.
var w = window.innerWidth;
var h = window.innerHeight;
var ow = window.outerWidth; //including toolbars and status bar etc.
var oh = window.outerHeight;
两者都返回整数并且不需要 jQuery。跨浏览器兼容。
我经常发现 jQuery 为 width() 和 height() 返回无效值
为什么没人提到matchMedia?
if (window.matchMedia("(min-width: 400px)").matches) {
/* the viewport is at least 400 pixels wide */
} else {
/* the viewport is less than 400 pixels wide */
}
没有测试那么多,但使用android默认和android chrome浏览器,桌面chrome进行了测试,到目前为止它看起来运行良好。
当然,它不返回数字值,而是返回布尔值——如果匹配或不匹配,那么可能不完全符合问题,但无论如何这就是我们想要的,可能是问题的作者想要的。
从 W3schools 及其跨浏览器回到 IE 的黑暗时代!
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
alert("Browser inner window width: " + w + ", height: " + h + ".");
</script>
</body>
</html>