簡體   English   中英

調整窗口大小時保持div的長寬比

[英]Keep aspect ratio of div when resizing window

我有一個很難解釋的問題。 我有一個高寬比為2:1的div。 我希望它具有基於瀏覽器窗口大小的100%寬度或高度。

如果窗口高度大於divs高度,則尺寸應基於100%寬度。

並且如果窗口高度小於divs高度,則尺寸應基於100%的高度。

用我的方法,當我放大時,它會閃爍。

請查看此鏈接http://acozmo.com/me/以獲取演示。

HTML

<section id="container">
</section>

JQuery的

function update() {

        var $documentHeight = $(document).height();
        var $windowHeight = $(window).height();
        var $documentWidth = $(document).width();
        var $windowWidth = $(window).width();

        var $container = $('#container');

        if ( $windowHeight >= $documentHeight ) {
            $container.width($windowWidth);
            $container.height($windowWidth / 2);
        }
        if ( $windowHeight < $documentHeight ) {
            $container.width($windowHeight * 2);
            $container.height($windowHeight);
        }
    }

    $(document).ready(function() {
        update()
    });

    $(window).resize(function() {
        update();
    })

要在保持寬高比的同時調整大小以適合窗口,請設置容器的初始尺寸,然后將區域寬度除以容器的寬度以得到比例。 然后,您需要檢查以確保比例尺不會使高度過大。 請參見下面的代碼和小提琴 -為了完整性,我添加了高度也大於寬度的情況。

要停止閃爍,請使用setTimeout限制調整大小功能。 這樣可以確保每n毫秒僅調用一次更新。 您可以玩數字游戲,直到找到合適的余額為止。

var container = $('#container'),
    updateTimeout,
    threshold = 100;

function update() {
    var windowWidth = $(window).width(),
        windowHeight = $(window).height(),
        width = container.width(),
        height = container.height(),
        scale;

    if ( windowWidth > windowHeight ) {
        scale = windowWidth / width;
        if ( height * scale > windowHeight ) {
            scale = windowHeight / height;
        }
    }
    else {
        scale = windowHeight / height;
        if ( width * scale > windowWidth ) {
            scale = windowWidth / width;
        }
    }
    container.width(Math.round(width * scale));
    container.height(Math.round(height * scale));
}

$(document).ready(function() {
    update();
});

$(window).resize(function() {
    clearTimeout(updateTimeout);
    updateTimeout = setTimeout(update, threshold);
});

這可能是因為您使用的是第二個if而不是else 它擊中第一個if ,縮小高度,然后擊中第二個if並增加它。

嘗試更改此設置( if是第二個):

if ( $windowHeight < $documentHeight ) {

對此:

else {

暫無
暫無

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

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