有時候網(wǎng)頁太長茉继,我們想要回到網(wǎng)頁頂部很麻煩谎脯。
這時候我們需要一個返回頂部的效果。
要實(shí)現(xiàn)返回頂部澳化,有很多方法崔步。
1.使用HTML的錨標(biāo)記是最簡單的方法。
但是缺點(diǎn)是樣式不好看
例子:<a href="top" id='top'></a>?標(biāo)簽只要靠近頂部就行
<a href='#top' target='_self'>返回頂部</a>
2.使用Scroll函數(shù)返回頂部
scrooll函數(shù)用來控制滾動條的位置缎谷,有兩種很簡單的實(shí)現(xiàn)方式:
(1):
返回頂部
scroll第一個參數(shù)是水平位置井濒,第二個參數(shù)是垂直位置,比如要想定位在垂直520像素處列林,改成scroll(0,520)就可以了瑞你。
(2)緩慢向上:
這個方法是漸進(jìn)式的返回頂部,比上一種好看一些:
例子:
functionpageScroll() {window.scrollBy(0,-10);scrolldelay=setTimeout('pageScroll()',100);}
<a href="pageScroll()">返回頂部</a>
這樣就會動態(tài)返回頂部希痴,只不過雖返回頂部但是代碼仍在運(yùn)行者甲,還需要停止掉。
if(document.documentElement.scrollTop==0)clearTimeout(scrolldelay)
3.用JQuery動畫來實(shí)現(xiàn)
這里用到了jquery的自定義動畫來實(shí)現(xiàn)功能
$('html, body').animate({ scrollTop: 0 },'fast')
4.不用動畫的jQuery
例子:
$('html,body').scrollTop(0);
5.純js 無動畫版本
window.scrollTo(0,0)
6.純js 動畫版本
生硬版:
varscrollToTop=window.setInterval(function() {
varpos=window.pageYOffset;
if?(?pos>0?)?{
window.scrollTo(?0,?pos?-?20?);?//?how?far?to?scroll?on?each?step
}?else?{
window.clearInterval(?scrollToTop?);
}
},?16);?//?how?fast?to?scroll?(this?equals?roughly?60?fps)
流暢版:
(function smoothscroll(){
varcurrentScroll=document.documentElement.scrollTop?||?document.body.scrollTop;
if?(currentScroll>0)?{
window.requestAnimationFrame(smoothscroll);
window.scrollTo?(0,currentScroll?-?(currentScroll/5));
}
})();