網站搜尋

html - 如何使用 JavaScript 代碼獲取瀏覽器寬度?


我正在嘗試編寫一個 JavaScript 函數來獲取當前瀏覽器的寬度。

我找到了這個:

console.log(document.body.offsetWidth);

但是它的問題是,如果 body 的寬度為 100% 就會失敗。

還有其他更好的功能或解決方法嗎?

答案#1

真是麻煩透了。我建議跳過這些無聊的東西,直接使用 jQuery,它可以讓你直接使用 $ (window).width()。

答案#2

2017 年更新

我最初的答案是在 2009 年寫的。雖然它仍然有效,但我想將它更新到 2017 年。瀏覽器仍然可能表現不同。我相信 jQuery 團隊能很好地維護跨瀏覽器的一致性。然而,沒有必要包含整個庫。在 jQuery 資源碼中,相關部分位於 dimensions.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。

答案#3

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() 的值不正確

答案#4

為什麼沒有人提到 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,到目前為止看起來運作良好。

當然,它不會返回數字值,而是返回布林值——是否匹配,因此可能不完全符合問題,但這正是我們想要的,也可能是問題的作者想要的。

答案#5

從 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>