利用jQuery 讓background-image達到responsive 效果

background-image在內容沒有設定height或裡面沒有物件時是不會顯示出來的。這種方式可以讓background-image得到height,並且在視窗縮小時自動跟著縮放。

Step 1:首先我們先在html裡面建立div

<div id="img00">
            <div class="img00Title"> </div>
            <div class="img00good"></div>
        </div>

Step 2:接著針對div去寫background-image

#img00Visual {
    background: url(../images/header/banner.png);
    @include background-size(cover);
    background-repeat: no-repeat;
    // @include zoomIn();
    #img00 {
        position: relative;
    }
    .img00Title {
        background: url(../images/content/title.png);
        @include background-size(cover);
        background-repeat: no-repeat;
        position: absolute;
        @include bounceInLeft(1s,1s,1s);
    }
    .img00good {
        background: url(../images/content/title_good.png);
        @include background-size(100%);
        background-repeat: no-repeat;
        position: absolute;
         @include bounceInLeft(1s,1s,2s);
    }
}

Step 3:接著寫入Jqueury

  $(document).ready(function() {
    var layout = function() { //將一個function存進變數
        var winW = $(window).width(); //先把window寬度存成變數
        var defW = 1920;//定義視窗最大寬度
        $('#img00').css({
            height: winW * (850 / defW) + 'px'//指定當前div的css height=window寬度*(圖片寬度/defW)
        });
        $('.img00Title').css({
            width: winW * (500 / defW) + 'px',
            height: winW * (120 / defW) + 'px',
            left: winW * (50 / defW) + 'px',
            top: winW * (60 / defW) + 'px'
        });

        $('.img00good').css({
            width: winW * (400 / defW) + 'px',
            height: winW * (120 / defW) + 'px',
            left: winW * (50 / defW) + 'px',
            top: winW * (190 / defW) + 'px'
        });
 };
$(window).resize(layout); //接著使用resize(變數名)
    layout(); 
    });

接著到chrome開啟檢視元素拖動視窗就會看到高度隨著視窗寬度在做變化囉