傳統錨點(<a href="#top">)只能瞬間跳,沒有過渡動畫。改用 jQuery 的 animate() 就能做出平滑捲動的效果。
<script type="text/javascript">
jQuery(function(){
$('#tophovertree').click(function(){
$('html,body').animate({ scrollTop: '0px' }, 1000);
return false;
});
$('#foothovertree').click(function(){
$('html,body').animate({ scrollTop: $(document).height() }, 1000);
return false;
});
})
</script>
兩個按鈕共用同一套邏輯,只差在捲動目標:回到頂部是 0px,跳到底部是 $(document).height()。1000 代表動畫歷時一秒,可依需求調整;數值越小越快。
一樣要留意 return false,用來阻止 href="#" 造成的跳轉與網址變化。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery實現"跳到底部","回到頂部"效果(類似錨)</title>
<script type="text/javascript" src="https://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
jQuery(function(){
$('#tophovertree').click(function(){ $('html,body').animate({scrollTop: '0px'}, 1000);return false;});
$('#foothovertree').click(function(){ $('html,body').animate({scrollTop:$(document).height()},1000);return false;});
})
</script>
</head>
<body>
<a href="#" id="foothovertree">跳到底部</a>
<br /><br /><br /><br />
<a href="#" id="tophovertree"> 返 回 頂 部 </a>
<br /><br /><br /><br />
<a name="footerhovertree" id="footerhovertree"></a>
</body>
</html>
最後那個 <a name="footerhovertree"> 保留了傳統錨點的做法,若你希望網址列帶上可被分享的錨點,可以在動畫的 callback 中改用 location.hash 設定,兼得平滑效果與可分享性。
返 回 頂 部