長頁面底部的「跳到底部」按鈕,用 jQuery 一行就能完成。
體驗效果:https://hovertree.com/texiao/jquery/9.htm
<script>
$('#hovertreetofoot').click(function () {
$('html,body').animate({ scrollTop: $(document).height() }, 1000);
return false;
});
</script>
原理是把捲動目標設為 $(document).height(),也就是整個頁面的總高度。由於捲動位置不可能超過最大值,瀏覽器會自動停在真正的底部,不必自己減去視窗高度。
兩個細節值得注意:選擇器同時寫 'html,body' 是為了相容不同瀏覽器(部分靠 html 捲動、部分靠 body);最後的 return false 則是阻止 <a href="#"> 的預設跳轉行為,否則網址會多出井字號。
範例中的按鈕用 position:fixed 固定在頁面頂部區域,讓使用者隨時都能看到:
<div style="position:fixed;left:0px;right:0px;width:120px; margin-left:auto;margin-right:auto;top:130px;background-color:silver"> <a id="hovertreetofoot" style="color:red" href="javascript:;">跳到底部</a> </div>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>跳到底部 jquery效果 - 何問起</title>
<meta charset="utf-8" />
<style> a{color:white} body{margin:0px} </style>
<script type="text/javascript" src="https://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script>
</head>
<body>
<div style="position:fixed;left:0px;right:0px;width:120px;margin-left:auto;margin-right:auto;top:130px;background-color:silver">
<a id="hovertreetofoot" style="color:red" href="javascript:;">跳到底部</a>
</div>
<div style="background-color:#959822; width:100%;height:150px;">請點擊本頁面的 跳到底部 鏈接體驗效果</div>
<div style="background-color:Green; width:100%;height:150px;">hovertree.com</div>
<div style="background-color:Red; width:100%;height:150px;">歡迎</div>
<div style="background-color:Olive; width:100%;height:350px;">何問起 返回頂部</div>
<div style="height:130px;"></div>
<script>
$('#hovertreetofoot').click(function () {
$('html,body').animate({ scrollTop: $(document).height() }, 1000); return false;
});
</script>
</body>
</html>