CSS 程式碼:
.scroll-up {
background: #dcdcdc url('up.png') no-repeat center center;
width:48px !important;
height:48px !important;
_width: 58px; /* for IE6 */
_height: 58px;
position: fixed;
_position: absolute; /* for IE6 fixed bug */
opacity: .6;
filter: Alpha(opacity=60);
padding:5px;
cursor: pointer;
display: none;
border-radius:5px;
-webkit-transition-property: background-color, opacity;
-webkit-transition-duration: 1s;
-webkit-transition-timing-function: ease;
-moz-transition-property: background-color;
-moz-transition-duration: 1s;
-moz-transition-timing-function: ease;
}
.scroll-up:hover {
background-color:#B9B9B9;
opacity: .8;
}
以下是 jQuery 程式碼:
;(function($) {
$.scrollBtn = function(options) {
var opts = $.extend({}, $.scrollBtn.defaults, options);
var $scrollBtn = $('<DIV></DIV>').css({
bottom: opts.bottom + 'px',
right: opts.right + 'px'
}).addClass('scroll-up').attr('title', opts.title)
.click(function() {
$('html, body').animate({scrollTop: 0}, opts.duration);
}).appendTo('body');
// 綁定 window 的 scroll 事件
$(window).bind('scroll', function() {
var scrollTop = $(document).scrollTop(),
viewHeight = $(window).height();
if(scrollTop <= opts.showScale) {
if($scrollBtn.is(':visible')) $scrollBtn.fadeOut(500);
} else {
if($scrollBtn.is(':hidden')) $scrollBtn.fadeIn(500);
}
// 解決 IE6 下 fixed 無效的問題
if(isIE6()) {
var top = viewHeight + scrollTop - $scrollBtn.outerHeight() - opts.bottom;
$scrollBtn.css('top', top + 'px');
}
});
function isIE6() {
if($.browser.msie) {
if($.browser.version == '6.0') return true;
}
}
};
$.scrollBtn.defaults = {
showScale: 100, // 超過 100px 顯示按鈕
right: 10,
bottom: 10,
duration: 200, // 回到頂部的時間
title: 'back to top'
}
})(jQuery);
呼叫範例:
$.scrollBtn({
showScale: 200, // 下滾 200px 後顯示按鈕
bottom: 20,
right: 20
});
這個元件會在頁面滾動超過設定門檻時淡入顯示,點擊後以動畫平滑回到頂端,並針對 IE6 不支援 position:fixed 的問題做了相容處理。