background
Recently, the development company’s official account H5 has made a function of clicking icon to scroll to the top. The implementation function is relatively simple, directly call window.scrollTo(0, 0), a line of code to complete. However, as a siege lion, it is impossible to set such low standards on myself, so I added a requirement for myself to implement smooth scrolling to the top of the page function. After investigation and review of documents, the following three schemes have emerged.
1. Using CSS
To achieve the highest level of functionality, just use CSS. The code is as follows:
html {
scroll-behavior: smooth;
}
Copy the code
This style specifies a scrolling behavior for the scrollbar element, but only when the user manually navigates or the CSSOM scrolling API triggers scrolling. Just as I was celebrating, I opened Can I Use to check compatibility:
2. Use the window.scrollto API
We all know window.scrollto (x, y), which scrolls to a location on the page by passing in the x and y coordinates of the document. The API can also pass in an option, which is an object with a left value corresponding to x, a top value corresponding to Y, and a behavior value that allows you to customize the scroll behavior. Then we can implement the scroll to the top like this:
window.scrollTo({
left: 0,
top: 0,
behavior: 'smooth'
})
Copy the code
That smells good. Done. A few days later, the product manager came to me with a 5-meter knife, saying that the scrolling effect on Safari was strange and the physical examination was very poor. So I silently opened the MDN document and scrolled to the bottom:
3. Use requestAnimationFrame
RequestAnimationFrame (requestAnimationFrame) we’ve seen a lot of requestAnimationFrame (requestAnimationFrame) but haven’t had the opportunity to use it. We know that requestAnimationFrame tells the browser to execute the incoming callback before the next redraw, which the browser does automatically for you. So here’s the code:
const scrollToTop = () => {
let sTop = document.documentElement.scrollTop || document.body.scrollTop
if (sTop > 0) {
window.requestAnimationFrame(scrollToTop)
window.scrollTo(0, sTop - sTop / 8)
}
}
Copy the code
Done!!!!!! Perfect!!!!!! While jumping around, I still open Can I Use to check requestAnimationFrame compatibility: