73

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

var viewportHeight = window.innerHeight || 
                     document.documentElement.clientHeight || 
                     document.body.clientHeight;

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

有没有更正确的方法来获取这些信息?理想情况下,我希望该解决方案也可以与 Safari/Chrome/其他浏览器一起使用。

4

5 回答 5

95

你可以试试这个:

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];
}

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

但是,甚至不可能在所有浏览器中获取视口信息(例如 IE6 在 quirks 模式下)。但是上面的脚本应该做得很好:-)

于 2010-01-09T22:25:51.690 回答
20

您可以使用较短的版本:

<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>
于 2011-10-14T09:59:14.087 回答
17

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

于 2009-11-19T22:21:35.897 回答
6

试试这个..

<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>
于 2014-03-08T07:39:02.323 回答
1

使用此提示:http: //www.appelsiini.net/projects/viewport或该代码:http ://updatepanel.wordpress.com/2009/02/20/getting-the-page-and-viewport-dimensions-using -jquery/

于 2009-11-21T12:22:49.467 回答