问题
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