長頁面裡放一對「往上」「往下」的按鈕,是很貼心的設計。原理單純得令人意外:scroll 函式接受水平與垂直座標,只要在一個迴圈裡讓垂直值逐步遞增,畫面就會連續捲動。
<script>
function scrollit() { // 向下捲
for (var I = 1; I <= 750; I++) {
scroll(1, I);
}
}
function scrollit1() { // 向上捲
for (var I = 750; I > 1; I = I - 1) {
scroll(1, I);
}
}
</script>
<form>
<div align="center">
<input type="button" value="向下捲屏" onClick="scrollit()">
</div>
</form>
<form>
<div align="center">
<input type="button" value="向上捲屏" onClick="scrollit1()">
</div>
</form>
水平座標固定寫 1、垂直座標從 1 數到 750,就是「原地往下捲 750 像素」;反過來遞減就是回頂。兩個函式幾乎一樣,只有迴圈方向不同。
今天不需要自己算座標,瀏覽器已經內建平滑捲動:
<button onclick="scrollBy({top: 400, behavior: 'smooth'})">往下看</button>
<button onclick="scrollTo({top: 0, behavior: 'smooth'})">回到頂端</button>
scrollBy 是相對目前位置移動,scrollTo 是移到絕對位置,加上 behavior: 'smooth' 就有原生的緩動效果。若要計算頁面總高度,用 document.documentElement.scrollHeight 就能取代寫死的 750。