傳統的"Return to Top"置于頁面底部或指定位置,點擊后返回頁面頂部。
但其存在諸多不便:
1、頁面頂部必須定義一個相應的錨點,其本身也會占用DOM空間,很容易發生返回的不是絕對的頂部而是該錨點(滾動條會稍微向下一點,而不是在0的位置)
2、如果頁面很長,想在滾動條任意處回頂部會變得難以處理。
使用jQuery能大大改善這一用戶體驗。本文章將能做到:
"Return to Top"在頁面初始化時不顯示,當移動滾動條時出現并隨滾動條位置變化而變化。
點擊"Return to Top"頁面移動到頂部,當滾動條到頂部時"Return to Top"自動隱藏。
以上均伴有動畫效果。
在線Demo:http://atealxt.appspot.com/guestbook
下載實例:http://www.tkk7.com/Files/atealxt/returnToTop.zip
首先有一個DIV
<div id="switcher">
<a href="#top" class="return-to-top">Return to Top</a>
</div>
其對應的CSS為
#switcher {
position: absolute;
width: 90px;
padding: .5em;
border: 1px solid #777;
background: #ddd;
}
.return-to-top {
clear: left;
}
在document.ready中令"Return to Top"移動到頁面最右邊,并隱藏。
$switcher.animate({
'left': $('#container').outerWidth() - $switcher.outerWidth()
}, function() {
$document.bind('scroll', moveSwitcher);
}
);
$switcher.hide();
綁定scroll事件要注意,要想支持IE6的話,必須用$window來綁定scroll事件。
函數moveSwitcher實現"Return to Top"隨滾動條移動而移動。
這里設定了一個事件延遲捕捉,以達到動畫效果。
var moveSwitcher = function() {
var delay = 500;
var executionTimer;
return function() {
if (!!executionTimer) {
clearTimeout(executionTimer);
}
executionTimer = setTimeout(function() {
$switcher.animate({ 'top': $window.height() + $document.scrollTop() - $switcher.height() - 25 }, 'slow', slideSwitcher);
}, delay);
};
}();
函數slideSwitcher為頁面移動到頂部時隱藏"Return to Top"。
var slideSwitcher = function() {
if ($document.scrollTop() == 0) {
$switcher.slideUp('fast');
} else {
$switcher.slideDown('fast');
}
};
為了完善這一效果,我們給resize事件也綁定moveSwitcher
$window.resize(function(){
$switcher.animate({ 'left': $('#container').outerWidth() - $switcher.outerWidth() } , moveSwitcher);
});
最后,給"Return to Top"添加onclick事件
1 $document.ready(function() {
2
3 $('a.return-to-top').click(function() {
4 $('html').animate({scrollTop: 0}, 'fast');
5 $('body').animate({scrollTop: 0}, 'fast');
6 return false;
7 });
8 });
第5行是專門為chrome和safari而追加的(感謝同學提醒)
參考http://stackoverflow.com/questions/1830080/jquery-scrolltop-doesnt-seem-to-work-in-safari-or-chrome-windows
好了,大功告成了。其實需要寫的代碼很少,真是贊嘆jQuery的強大:D