繁体   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