以純 CSS 或 JavaScript 完成三個網頁平滑滾動的方法。
方法一-純 CSS
HTML 中設定 a
標籤錨點為對應區塊的 id
,即具備默認的滾動效果。
1 2 3 4 5 6 7 8
| <nav class="nav"> <a href="#section1" class="btn">section 01</a> <a href="#section2" class="btn">section 02</a> <a href="#section3" class="btn">section 03</a> </nav> <div class="full-page" id="section1">section 01</div> <div class="full-page" id="section2">section 02</div> <div class="full-page" id="section3">section 03</div>
|
之後在 CSS 中的 html
標籤上設定 scroll-behavior
屬性,使頁面平滑滾動。
1 2 3
| html { scroll-behavior: smooth; }
|
實際效果 :
1 2 3 4 5 6 7 8
| <nav class="nav"> <button class="btn" data-section="#section1">section 01</button> <button class="btn" data-section="#section2">section 02</button> <button class="btn" data-section="#section3">section 03</button> </nav> <div class="full-page" id="section1">section 01</div> <div class="full-page" id="section2">section 02</div> <div class="full-page" id="section3">section 03</div>
|
使用 scrollIntoView()
方法,將調用方法的元素顯示到視窗中。
1 2 3 4 5 6 7 8 9 10 11
| const btns = document.querySelectorAll(".btn") const section1 = document.querySelector("#section1") const section2 = document.querySelector("#section2") const section3 = document.querySelector("#section3")
btns.forEach(btn => btn.addEventListener("click", e => { const section = document.querySelector(e.target.dataset.section) section.scrollIntoView({ behavior: "smooth" }) }) )
|
實際效果 :
HTML 配置與方法二相同。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const btns = document.querySelectorAll(".btn") const section1 = document.querySelector("#section1") const section2 = document.querySelector("#section2") const section3 = document.querySelector("#section3")
btns.forEach(btn => btn.addEventListener("click", e => { const section = document.querySelector(e.target.dataset.section) const coords = section.getBoundingClientRect() window.scrollTo({ top: coords.top + window.scrollY, behavior: "smooth", }) }) )
|
getBoundingClientRect()
取得元素的大小及相對於視窗中的位置。而在 scrollTo()
方法內,top
屬性中 coords.top
為目前元素相對視窗頂部的距離,所以還要加上 window.scrollY
即視窗已經滾動的距離,如此元素才能準確地顯示於視窗中。
實際效果 :
參考資料