2011-05-17 103 views

回答

4

爲了確定實際尺寸(使用javascript)瀏覽器窗口,使用以下屬性:

在Internet Explorer(向後兼容模式):

document.body.offsetWidth, document.body.offsetHeight 
在Internet Explorer

(標準模式,document.compatMode == 'CSS1Compat'):

document.documentElement.offsetWidth, document.documentElement.offsetHeight 
在大多數其他瀏覽器

window.innerWidth, window.innerHeight 
The following code sets the variables winW and winH to the actual width and height of the browser window, and outputs the width and height values. If the user has a very old browser, then winW and winH are set to 630 and 460, respectively. 

var winW = 630, winH = 460; 
if (document.body && document.body.offsetWidth) { 
winW = document.body.offsetWidth; 
winH = document.body.offsetHeight; 
} 
if (document.compatMode=='CSS1Compat' && 
    document.documentElement && 
    document.documentElement.offsetWidth) { 
winW = document.documentElement.offsetWidth; 
winH = document.documentElement.offsetHeight; 
} 
if (window.innerWidth && window.innerHeight) { 
winW = window.innerWidth; 
winH = window.innerHeight; 
} 

document.writeln('Window width = '+winW); 
document.writeln('Window height = '+winH); 

在瀏覽器中,此代碼產生以下輸出:

Window width = 1280 
Window height = 675 

注:

  1. 如果上面的代碼框架或iframe中執行,它會給你的幀的寬度和高度。
  2. 計算出的寬度和高度不包括標題欄,菜單欄,狀態欄或工具欄 - 但可能包含水平和垂直滾動條(如果有)。
  3. 應該在瀏覽器解析標籤後執行使用document.body.offsetWidth和offsetHeight的代碼。
  4. 如果用戶調整瀏覽器窗口大小,則可能需要重新計算寬度和高度(使用window.onresize來實現)。
  5. 同樣,如果用戶放大(或縮小),您可能還需要重新計算寬度和高度。