簡體   English   中英

jQuery:在調整背景圖片大小的同時保持寬高比

[英]jquery: maintain aspect ratio whilst resizing a background image

我有一個現有網站,需要主頁上的背景圖像。

以下代碼在該網站上可以正常運行,但是我無法確定如何保持圖像的寬高比。

function resize(itemToResize){
var newHeight = $(document).height() -120,
    newWidth = $(window).width();
$(itemToResize).css({
    "width" : newWidth,
    "height" : newHeight
    });
};

我想我需要某種if語句,例如寬度是否與窗口寬度相同,而高度太小則無法匹配高度並調整寬度...我只是無法得出正確的語法!

更新:使用此處介紹的方法計算寬高比的算法是什么? 我需要一個輸出:4:3,16:9我可以訪問圖像的寬高比。 但是,現在我有了自己的比率,我不知道該怎么辦!

更新的代碼:-

function gcd (a, b) {
    return (b == 0) ? a : gcd (b, a%b);
    }

function resize(itemToResize){
var newHeight = $(document).height() -120,
    newWidth = $(window).width();

var w = $(itemToResize).width(),
    h = $(itemToResize).height(),
    r = gcd (w, h);

$(itemToResize).css({
    "width" : newWidth,
    "height" : newHeight
    });
};

更新2:

在插入了更長的時間后,我有了以下代碼:

function resize(itemToResize){  
var AspectRatio = $(itemToResize).width()/$(itemToResize).height();
var WindowHeight = $(document).height() -205;
var WindowWidth = $(window).width();
var AspectRatio = WindowWidth/WindowHeight;
if (AspectRatio >= AspectRatio) {
     $(itemToResize).css({
        "width" : WindowWidth,
        "height" : WindowWidth/AspectRatio
        }); 
     $('body').css({
        "height" : WindowWidth/AspectRatio
     });
} else {
    $(itemToResize).css({
        "width" : WindowHeight*AspectRatio,
        "height" : WindowHeight
        });
    $('body').css({
        "height" : WindowHeight
     });
    };

};

這保持了寬高比,但不能很好地拉伸。 如此修復,但僅部分解決。

有一些JQuery插件已經可以滿足您的要求;

  1. jQuery超大型-http: //buildinternet.com/project/supersized/
    超大尺寸允許幻燈片顯示和多個背景,但還具有單個背景,較小的代碼塊可供下載。

  2. jQuery Backstretch- http://srobbin.com/jquery-plugins/backstretch/

希望這可以幫助。

$(window).load(function() {
 var $win = $(this);
 var $img = $('#background').css({'position':'fixed','top':0,'left':0});
    function resize() {
        if (($win.width() / $win.height()) < ($img.width() / $img.height())) {
          $img.css({'height':'100%','width':'auto'});
        } else {
          $img.css({'width':'100%','height':'auto'});
        }
    }
    $win.resize(function() { resize(); }).trigger('resize');
});

暫無
暫無

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

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