半浮動DIV區域 part2

才寫了”半浮動DIV區域”這個文章 (link), 又發現還有另一種應用情境, 就是捲到下面, 若半浮動區域的底部觸到了 footer , 則要順勢往上, 不再固定.

參考應用如: http://www.yinshiweb.com/ 右側的側欄.

先來看看原始的長相, 一樣是上面 top, 中間 main, 並含有 content 及 flow_div 兩個區域, 還有最下方的 footer. 不含捲動的狀況如: http://sample.diary.tw/29/o.htm

接下來要加上程式碼, 原來的半浮動DIV區域, 只需要用 CSS 配合捲動 event 就可以達成, 但若在浮動區域觸底時, 要跟著捲動上去, 就必須將該 absolute css 的 top 位置用 footer 的 top 減去 flow_div 的高度才行, 不過這個值是動態的, 所以就只能在 runtime 時, 用 jQuery 的 css 屬性來給定, 先看浮動及跟著捲的兩個狀態配合的 css:

.fixed{
    position:fixed;
    top:0px;
}
.absolute{
    position: absolute;
    /*top: should be top2 value, modified by jQuery*/
}

其中的 absolute 的 top 得由後面的程式來給定及移除, javascript 如下:

$(document).ready(function(){
    // calculate the original top
    var top = $('#flow_div').offset().top - parseFloat($('#flow_div').css('marginTop').replace(/auto/, 0));
    var top2 = $('#footer').offset().top - $('#flow_div').height();     
    
    $(window).scroll(function (event){
        var y = $(this).scrollTop();
        if(y>=top){
            if(y<top2){
                // state 3.
                $('#flow_div').addClass('fixed');
                $('#flow_div').removeClass('absolute');
                $('#flow_div').css('top', '0px');
            }else{
                // state 2.
                $('#flow_div').removeClass('fixed');
                $('#flow_div').addClass('absolute');
                $('#flow_div').css('top', top2 + 'px');
            }
        }else{
            // state 1.
            $('#flow_div').removeClass('fixed');
            $('#flow_div').removeClass('absolute');
            $('#flow_div').css('top', '0px');
        }
    });    
});

一樣要先算出 top 及 top2 兩個值, 然後在 scroll event 中判斷三種狀況,
state 1. 原始狀態, 還沒捲到 flow_div
state 2. 捲到 flow_div 了, 但底部還未頂到 footer
state 3. 捲到 flow_div 底部頂到 footer 了

完成的結果請參考: http://sample.diary.tw/29/2.htm

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *