以跨浏览器的方式查找视口的确切高度和宽度(无原型/ jQuery)

Ale*_*rin 65 javascript cross-browser viewport

我试图找到浏览器视口的确切高度和宽度,但我怀疑Mozilla或IE正在给我错误的数字.这是我的身高方法:

var viewportHeight = window.innerHeight || 
                     document.documentElement.clientHeight || 
                     document.body.clientHeight;
Run Code Online (Sandbox Code Playgroud)

我还没有开始宽度,但我猜它会有类似的东西.

是否有更正确的方法来获取此信息?理想情况下,我也希望该解决方案能够与Safari/Chrome /其他浏览器配合使用.

Leo*_*Leo 89

你可以试试这个:

function getViewport() {

 var viewPortWidth;
 var viewPortHeight;

 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 if (typeof window.innerWidth != 'undefined') {
   viewPortWidth = window.innerWidth,
   viewPortHeight = window.innerHeight
 }

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
 else if (typeof document.documentElement != 'undefined'
 && typeof document.documentElement.clientWidth !=
 'undefined' && document.documentElement.clientWidth != 0) {
    viewPortWidth = document.documentElement.clientWidth,
    viewPortHeight = document.documentElement.clientHeight
 }

 // older versions of IE
 else {
   viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
   viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
 }
 return [viewPortWidth, viewPortHeight];
}
Run Code Online (Sandbox Code Playgroud)

(http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/)

但是,甚至无法在所有浏览器中获取视口信息(例如,在怪异模式下的IE6).但上面的脚本应该做得很好:-)

  • 卡住了5个小时的bug,结果jquery在执行`$(document).width()`或`$(window).width()`时不会在FF/Chrome中返回相同的值.`window.innerWidth`效果很好. (4认同)
  • @GarciaWebDev 所以你的意思是它工作正常;-) (2认同)

dzo*_*ona 19

你可以用更短的版本:

<script type="text/javascript">
<!--
function getViewportSize(){
    var e = window;
    var a = 'inner';
    if (!('innerWidth' in window)){
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}
//-->
</script>
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 16

我一直只用document.documentElement.clientHeight/ clientWidth.在这种情况下,我认为你不需要OR条件.

  • 同意`document.documentElement.clientWidth`是纯JS的方法.http://responsejs.com/labs/dimensions/ (4认同)
  • 你有错字,应该是:'document.documentElement'.这在quircksmode中不起作用...在FF上它给出了整个文档的高度,而不仅仅是'clientHeight',而在IE上它给出'0'. (2认同)

Mat*_*thi 5

试试这个..

<script type="text/javascript">
function ViewPort()
{
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
var viewsize = w + "," + h;
alert("Your View Port Size is:" + viewsize);
}
</script>
Run Code Online (Sandbox Code Playgroud)