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

核能气质少年 提交于 2020-01-01 14:39:24

问题


Is there any reason why this code would work in Safari and Chrome but not IE or 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="" />

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;

回答1:


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

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



回答2:


Use jQuery methods which support almost all the browsers.

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

Reference: width(), height()




回答3:


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

Here are some good docs for window.outerWidth: https://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 px or em) then you can use .css('width') and .css('height').



来源:https://stackoverflow.com/questions/9182811/js-to-detect-browser-width-and-height-works-in-chrome-safari-but-not-ie9-or-ff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!