我试图写一个JavaScript函数,以获得当前的浏览器宽度。
我找到了这个:
console.log (document.body.offsetWidth);
但问题是,如果主体宽度为100%,它就会失败。
还有其他更好的功能或解决方案吗?
我试图写一个JavaScript函数,以获得当前的浏览器宽度。
我找到了这个:
console.log (document.body.offsetWidth);
但问题是,如果主体宽度为100%,它就会失败。
还有其他更好的功能或解决方案吗?
当前回答
下面是上面函数的一个简短版本:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
else if (document.documentElement && document.documentElement.clientHeight){
return document.documentElement.clientWidth;
}
else if (document.body) {
return document.body.clientWidth;
}
return 0;
}
其他回答
下面是上面函数的一个简短版本:
function getWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
else if (document.documentElement && document.documentElement.clientHeight){
return document.documentElement.clientWidth;
}
else if (document.body) {
return document.body.clientWidth;
}
return 0;
}
这很麻烦。我建议跳过这些废话,使用jQuery,它让你只需要执行$(window).width()。
从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>
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()的无效值。
一个适应的解决方案,现代JS的特拉维斯的答案:
const getPageWidth = () => {
const bodyMax = document.body
? Math.max(document.body.scrollWidth, document.body.offsetWidth)
: 0;
const docElementMax = document.documentElement
? Math.max(
document.documentElement.scrollWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth
)
: 0;
return Math.max(bodyMax, docElementMax);
};