2011-02-12 67 views
5

我希望通過多種瀏覽器獲得可用窗口大小的方法沒有使用jQuery/Mootools /任何第三方庫依賴項。我在這方面做了一些研究,但是我遇到的一半是關於Netscape Navigator的內容...在多個瀏覽器中一致地獲取可用的瀏覽器窗口大小(clientHeight/clientWidth)

想知道如果有人有更近期的建議。

+0

那麼,第三方庫對於減少像這樣的事情的開發是非常好的,這不需要很長時間,但是它的確如此,因爲JavaScript在所有瀏覽器中都不一致:p我建議打開jQuery或Mootools並檢查它使用的代碼(推測這是安全的,跨瀏覽器兼容的JavaScript) – 2011-02-12 07:41:43

回答

5

用法

var width = getWindowSize().width; 

代碼

var getWindowSize = (function() { 
    var docEl = document.documentElement, 
     IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0; 

    // Used to feature test Opera returning wrong values 
    // for documentElement.clientHeight. 
    function isDocumentElementHeightOff() { 
     var d = document, 
      div = d.createElement('div'); 
     div.style.height = "2500px"; 
     d.body.insertBefore(div, d.body.firstChild); 
     var r = d.documentElement.clientHeight > 2400; 
     d.body.removeChild(div); 
     return r; 
    } 

    if (typeof document.clientWidth == "number") { 
    return function() { 
     return { width: document.clientWidth, height: document.clientHeight }; 
    }; 
    } else if (IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) { 
     var b = document.body; 
     return function() { 
     return { width: b.clientWidth, height: b.clientHeight }; 
     }; 
    } else { 
     return function() { 
     return { width: docEl.clientWidth, height: docEl.clientHeight }; 
     }; 
    } 
})(); 

注:尺寸不能被精確地確定,直到文檔完成加載之後。

comp.lang.javascript FAQ

4

這不是一個完美的解決方案,但它是輕量級的適用於大多數情況&:

var WX,WY; 
if(window.innerWidth) 
{ 
    WX = window.innerWidth; 
    WY = window.innerHeight; 
} else { 
    WX = document.body.clientWidth; 
    WY = document.body.clientHeight; 
} 
2

對於現代的瀏覽器:

document.documentElement.clientHeight 

是所有你需要。