DIV CSS 佈局教程網

用 jQuery 實作返回頂部按鈕(相容 IE6)
編輯:JQuery特效代碼     

長頁面一定需要的返回頂部按鈕。用 jQuery 做除了簡單,還能順手處理 IE6 這個老對手。

HTML 結構

<div class="scroll"></div>
<script type="text/javascript" src="../skins/css/jQuery.js" charset="UTF-8"></script>
<script type="text/javascript" src="../skins/css/top.js" charset="UTF-8"></script>

CSS:用 expression 硬扛 IE6

.scroll{
    background: url(../image/scroll.gif) no-repeat center top transparent;
    bottom: 100px;
    cursor: pointer;
    height: 67px;
    width: 18px;
    position: fixed;
    _position: absolute;   /* 兼容 IE6:它不認得 fixed */
    /* 700 為圖片距頂部的設定距離,可自行調整;不加 700 則圖片緊貼頂部滾動 */
    _top: expression(eval(document.documentElement.scrollTop) + 700);
}
html{ _text-overflow: ellipsis; }   /* 解決 IE6 下圖片抖動 */

下底線前綴(_position、_top)是 IE6 專屬的 hack,其他瀏覽器會直接忽略。IE6 不支援 position: fixed,只能用 expression 動態計算 top 來模擬。

JavaScript:定位、點擊與動態顯示

$(document).ready(function(){
    var show_delay;
    // 960 為頁面寬度,計算按鈕應該貼在右側的位置
    var scroll_left = parseInt((document.body.offsetWidth - 960) / 2) + 961;

    $(".scroll").click(function (){
        document.documentElement.scrollTop = 0;
        document.body.scrollTop = 0;      // 兩行都要,分別應對標準模式與 IE  quirks
    });

    $(window).resize(function (){
        scroll_left = parseInt((document.body.offsetWidth - 960) / 2) + 961;
        $(".scroll").css("left", scroll_left);
    });

    reshow(scroll_left, show_delay);
});

function reshow(marign_l, show_d) {
    $(".scroll").css("left", marign_l);
    if ((document.documentElement.scrollTop + document.body.scrollTop) != 0) {
        $(".scroll").css("display", "block");     // 已滾動 → 顯示
    } else {
        $(".scroll").css("display", "none");      // 在頂部 → 隱藏
    }
    if (show_d) window.clearTimeout(show_d);
    show_d = setTimeout("reshow()", 500);         // 每 500ms 重新判斷
}

幾點值得改進的地方

用 500ms 的 setTimeout 輪詢來判斷是否顯示,雖然簡單但並不省資源;直接監聽 $(window).scroll() 事件會即時得多,再搭配 scrollTop 的 animate 做平滑回頂,體驗更好。

另外 setTimeout("reshow()") 的字串寫法會隱含一次 eval,而且這裡沒有把 marign_l 與 show_d 傳進去,第二次之後其實用的是 undefined。改成 setTimeout(function(){ reshow(marign_l, show_d); }, 500) 就正常了。

最後别忘了引入 jQuery 本體,這是最容易漏的一步。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved