DIV CSS 佈局教程網

跨瀏覽器取得視窗尺寸與位置的 JS 寫法
編輯:關於JavaScript     

「取得瀏覽器視窗有多大」是彈出層置中、自適應佈局都要用到的基礎能力。麻煩的是標準瀏覽器與 IE 用的屬性名稱完全不同,需要一層相容處理。

取得視窗寬高

var pageWidth = window.innerWidth,
    pageHeight = window.innerHeight;

if (typeof pageWidth != "number") {
  if (document.compatMode == "CSS1Compat") {
    pageWidth = document.documentElement.clientWidth;
    pageHeight = document.documentElement.clientHeight;
  } else {
    pageWidth = document.body.clientWidth;
    pageHeight = document.body.clientHeight;
  }
}

邏輯分三層:先嘗試標準的 window.innerWidth / innerHeight;若不是數值(代表來到舊版 IE),再用 document.compatMode 判斷頁面是否處於標準模式;標準模式取 documentElement 的 clientWidth / clientHeight,怪胎模式( quirks mode)則退回 body 的對應屬性。

之所以要分模式,是因為 IE 在 quirks mode 下把 body 當成版面根元素,而在標準模式下根元素是 documentElement,兩者回報的尺寸並不相同。

取得視窗在螢幕上的位置

var leftPos = (typeof window.screenLeft == "number") ? window.screenLeft : window.screenX;
var topPos = (typeof window.screenTop == "number") ? window.screenTop : window.screenY;

同樣是二元運算子做特性偵測:IE、Safari、Opera、Chrome 提供 screenLeft / screenTop;Firefox 沒有這兩個屬性,必須改用 screenX / screenY。

順帶一提:捲動距離

實務上通常還會需要「頁面已經捲了多少」,寫法與上面同一個套路:

var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;

用 || 串接是因為其中一個在部分情境下會是 0,而 0 在標準模式下代表「真的沒捲」,在另一個屬性上則是 undefined,兩者都涵蓋才安全。

為什麼現在還要看這些

現代專案可以直接用 window.innerWidth、window.scrollY,並以 CSS 的 position: fixed 與 flex 置中取代手算座標。但理解「標準模式與怪胎模式差在哪」這件事仍然值得,因為很多老系統的排版怪象都源自 doctype 宣告不完整,導致整頁掉進 quirks mode。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved