2012-02-07 206 views
4

是否有任何理由爲什麼此代碼可以在Safari和Chrome,但不IE或FF?JS檢測瀏覽器的寬度和高度在Chrome瀏覽器和Safari瀏覽器,但不是IE9或FF9

JS

function load(){ 
    w.value = window.outerWidth; 
    h.value = window.outerHeight; 
} 

HTML

<input name="h" id="h" type="hidden" value="" /> 
<input name="w" id="w" type="hidden" value="" /> 

Click here for the entire page's source code

預先感謝幫助。

編輯:我想出了什麼是錯的。必須將以下內容添加到加載功能

var width = document.getElementById("w"); 
var height = document.getElementById("h"); 
width.value = window.outerWidth; 
height.value = window.outerHeight; 
+1

有什麼不適合呢?它在做什麼,它沒有做什麼,發生了什麼錯誤等等。 – 2012-02-07 19:50:39

回答

4

Internet Explorer使用不同的屬性來存儲窗口大小。進入Internet Explorer客戶端寬度/高度是內部窗口大小(減去滾動條,菜單等使用的像素)所以請嘗試

function load(){ 
    if(window.outerHeight){ 
     w.value = window.outerWidth; 
     h.value = window.outerHeight; 
    } 
    else { 
     w.value = document.body.clientWidth; 
     h.value = document.body.clientHeight; 
    } 
} 
+0

你不妨使用jQuery的'.width()'/'.height()',這裏使用的代碼和你一樣已經包括與jQuery。 – Jasper 2012-02-07 20:10:41

4

使用支持幾乎所有瀏覽器的jQuery方法。

function load(){ 
    w.value = $(window).width(); 
    h.value = $(window).height(); 
} 

參考:width()height()

4

如果你正在使用jQuery的話,我建議使用.width().height(),因爲他們將正常運行跨瀏覽器。 IE 8及以下版本不支持window.outerWidth

下面是window.outerWidth一些很好的文檔:https://developer.mozilla.org/en/DOM/window.outerWidth

使用.width().height()將返回一個單位的數值(即像素),如果你想獲得精確的高度/寬度套(含pxem),那麼你可以使用.css('width').css('height')

相關問題