javascript 用于检测浏览器宽度和高度的 JS 在 Chrome 和 Safari 中有效,但不适用于 IE9 或 FF9

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9182811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:50:59  来源:igfitidea点击:

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

javascriptjqueryhtmlcross-browser

提问by Eric

Is there any reason why this code would work in Safari and Chrome but not IE or FF?

有什么理由为什么这段代码可以在 Safari 和 Chrome 中运行,但不能在 IE 或 FF 中运行吗?

JS

JS

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

HTML

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

单击此处获取整个页面的源代码

Thanks in advance for the assistance.

预先感谢您的帮助。

Edit: I figured out what was wrong. The following had to be added to the load function

编辑:我想出了什么问题。必须将以下内容添加到加载功能中

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

回答by ShankarSangoli

Use jQuery methods which support almost all the browsers.

使用支持几乎所有浏览器的 jQuery 方法。

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

Reference: width(), height()

参考:width(), height()

回答by comu87

Internet Explorer use different properties to store the window size. Into Internet Explorer clientWidth/Height is inner window size (subtract the pixels used by scroll bar, menu etc) so try

Internet Explorer 使用不同的属性来存储窗口大小。进入 Internet Explorer clientWidth/Height 是内部窗口大小(减去滚动条、菜单等使用的像素)所以试试

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

回答by Jasper

If you are using jQuery then I suggest using .width()and .height()because they will function properly cross-browser. window.outerWidthis not supported in IE 8 and below.

如果您使用的是 jQuery,那么我建议使用.width().height()因为它们可以跨浏览器正常运行。window.outerWidthIE 8 及以下不支持。

Here are some good docs for window.outerWidth: https://developer.mozilla.org/en/DOM/window.outerWidth

这里有一些很好的文档window.outerWidthhttps: //developer.mozilla.org/en/DOM/window.outerWidth

Using .width()and .height()will return a unit-less number (that is in pixels), if you want to get the exact height/width set (including pxor em) then you can use .css('width')and .css('height').

使用.width()and.height()将返回一个无单位的数字(即以像素为单位),如果您想获得精确的高度/宽度集(包括pxem),那么您可以使用.css('width')and .css('height')