# Smooth Scroll To 如果一個頁面的內容太長,通常會為了讓使用者體驗不要太差而在頁面的右下角加上一個往上的箭頭,點擊後就會回到頁面最上方,在一些臉書的社團常常會看到有人用jQuery來實作該部分,但我們也可以利用原生的Javascript來實作,程式碼不到5行。 會用那麼多文字的原因是因為要把畫面撐高。 ***index.html*** ```htmlembedded= <div class="goTop"> <img src="https://img-premium.flaticon.com/png/512/2267/premium/2267904.png?token=exp=1633625403~hmac=19e87d3285d74591879065f2a97e8afc" width="50" alt="Image Not Found" /> </div> <p>Lorem ipsum dolor sit amet.</p> <p>Lorem ipsum dolor sit amet.</p> <p>Lorem ipsum dolor sit amet.</p> <p>Lorem ipsum dolor sit amet.</p> <p>Lorem ipsum dolor sit amet.</p> <p>Lorem ipsum dolor sit amet.</p> ``` ***style.css*** ```css= p { font-size: 5em; } .goTop { background: #e13834; border-radius: 20px; width: max-content; padding: 0.5em; position: fixed; bottom: 10px; right: 10px; cursor: pointer; } ``` ***app.js*** ```javascript= const scrollToTop = () => { window.scrollTo({ top: 0, behavior: "smooth" }); }; document.querySelector(".goTop").addEventListener("click", scrollToTop); ``` ## CodeSandbox <iframe src="https://codesandbox.io/embed/scroll-to-top-n6xe9?fontsize=14&hidenavigation=1&theme=dark" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" title="Scroll to Top" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" ></iframe>