傳統(tǒng)的"Return to Top"置于頁面底部或指定位置,點(diǎn)擊后返回頁面頂部。
但其存在諸多不便:
1、頁面頂部必須定義一個(gè)相應(yīng)的錨點(diǎn),其本身也會占用DOM空間,很容易發(fā)生返回的不是絕對的頂部而是該錨點(diǎn)(滾動條會稍微向下一點(diǎn),而不是在0的位置)
2、如果頁面很長,想在滾動條任意處回頂部會變得難以處理。
使用jQuery能大大改善這一用戶體驗(yàn)。本文章將能做到:
"Return to Top"在頁面初始化時(shí)不顯示,當(dāng)移動滾動條時(shí)出現(xiàn)并隨滾動條位置變化而變化。
點(diǎn)擊"Return to Top"頁面移動到頂部,當(dāng)滾動條到頂部時(shí)"Return to Top"自動隱藏。
以上均伴有動畫效果。
在線Demo:http://atealxt.appspot.com/guestbook
下載實(shí)例:http://www.tkk7.com/Files/atealxt/returnToTop.zip
首先有一個(gè)DIV
<div id="switcher">
<a href="#top" class="return-to-top">Return to Top</a>
</div>
其對應(yīng)的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事件。
函數(shù)moveSwitcher實(shí)現(xiàn)"Return to Top"隨滾動條移動而移動。
這里設(shè)定了一個(gè)事件延遲捕捉,以達(dá)到動畫效果。
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);
};
}();
函數(shù)slideSwitcher為頁面移動到頂部時(shí)隱藏"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而追加的(感謝同學(xué)提醒)
參考http://stackoverflow.com/questions/1830080/jquery-scrolltop-doesnt-seem-to-work-in-safari-or-chrome-windows
好了,大功告成了。其實(shí)需要寫的代碼很少,真是贊嘆jQuery的強(qiáng)大:D