半浮動DIV區域

一般網頁利用CSS排版, 通常分為上中下三段, 分別為 top, main, footer.

其中在 main 做一些特效, 讓一個區域能在捲動時, 會固定在畫面上. 這樣的特效, 需要配合 javascript (或 jQuery ) 來進行才能達成, 先來看一下效果: link.

除了上(top), 中(main), 下(footer)外, 另外在 main 中還有一個 content 及 flow_div 兩個區域. 在向下捲動時, 若 flow_div 捲動超過畫面上方時, 則會變成固定在畫面上.

程式的實作方式利用 jQuery 來進行, 先看程式碼:

$(document).ready(function(){
    // calculate the original top
    var top = $('#flow_div').offset().top - parseFloat($('#flow_div').css('marginTop').replace(/auto/, 0));    
    $(window).scroll(function (event){
        var y = $(this).scrollTop();
        if(y>=top){
            $('#flow_div').addClass('fixed');
        }else{
            $('#flow_div').removeClass('fixed');
        }
    });
});

在 document ready 時, 先把 #flow_div 的 top 距離算出來, 接下來在 window 的 scroll event 裡, 把 window 的捲動距離算出來後, 和上述的 top 變數比較, 若是超過了, 就把 #flow_div 多加上一個 class 名為 fixed, 讓它固定, 反之則將 fixed class 移除, 也就是跟著畫面捲動.

其中 fixed class 內容重點在於: position: fixed; top: 0px; , 也就是固定在距離畫面上方為 0, 看起來就是浮在原來的內容之上, 若還沒有捲動, 就移除這個 class, 會跟著捲動.

很有意思的一個排版特效.

範例頁: http://sample.diary.tw/29/1.htm