簡體   English   中英

Javascript將瀏覽器視口大小輸出到body CSS中

[英]Javascript get browser viewport size an output into body CSS

我正在使用Andy Langton javascript來獲取我的視頻大小。 如果您還沒有聽說過,請參閱下面的鏈接。

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

該腳本可以工作,但我不確定這是讓腳本將'width'和'height'輸出到我的body CSS或其他任何CSS選擇器的最佳方法。

看看我下面的蹩腳嘗試,雖然我認為我在混淆jQuery時會出錯

<script>

    <!--

    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
    }

    $(document).ready(function() {

        $("body").css({
            width   : "+viewportwidth+",
            height  : "+viewportheight+"
        });

    });

    //-->

</script>

任何人都可以幫助我解決這個難題嗎?

如果有辦法通過PHP標簽將其添加到body html中,那也很酷,請參閱下面的示例...

<div style="width: <?php veiwportwidth(); ?>px; height: <?php veiwportheight(); ?>px;"> </div>

如果這是有道理的,不要擔心,如果沒有,只需javascript位將非常有幫助。

提前致謝。

你接近你的jQuery:

$( 'body' ).css( {
    'width'   : viewportwidth + 'px',
    'height'  : viewportheight + 'px'
} );

您還可以向DOM添加樣式部分,這有助於類重用(但在這種情況下不是很多):

演示: http//jsfiddle.net/ThinkingStiff/Pa9k3/

腳本:

var bodyStyle =
    'body'
    + '{'
    + 'width: ' + viewportwidth + 'px;'
    + 'height: ' + viewportheight + 'px;'
    + '}';

$( '<style />' ).append( 
    document.createTextNode( bodyStyle )
).appendTo( 'head' );

以下是您需要修復的內容:

$("body").css({
    width   : "+viewportwidth+",
    height  : "+viewportheight+"
});

至:

$("body").css({
    "width"   : viewportwidth + "px",
    "height"  : viewportheight + "px"
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM