簡體   English   中英

用於檢測瀏覽器寬度和高度的 JS 適用於 Chrome 和 Safari,但不適用於 IE9 或 FF9

[英]JS to detect browser width and height works in Chrome & Safari but not IE9 or FF9

這段代碼是否可以在 Safari 和 Chrome 中運行,但不能在 IE 或 FF 中運行?

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="" />

點擊這里查看整個頁面的源代碼

提前感謝您的幫助。

編輯:我知道出了什么問題。 必須將以下內容添加到加載功能

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

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; 
  }
}

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

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

參考:寬度()高度()

如果您使用的是 jQuery,那么我建議使用.width().height()因為它們可以跨瀏覽器正常工作。 IE 8 及更低版本不支持window.outerWidth

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

使用.width().height()將返回一個無單位的數字(以像素為單位),如果你想獲得確切的高度/寬度集(包括pxem ),那么你可以使用.css('width').css('height')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM