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 の互換モード)。しかし、上記のスクリプトはうまくいくはずです:-)

于 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 に答える
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 に答える