Recently, the development company's public account H5 has a function to scroll to the top by clicking on the icon. The function is relatively simple to implement. Just call window.scrollTo(0, 0) directly and complete it in one line of code. But as a siege lion, how could I have such low requirements for myself, so I added a requirement for myself to realize the function of smoothly scrolling the page to the top. After research and reviewing documents, we have the following three options.
1. Use CSSThe highest level of functionality can be accomplished using only CSS. The code is as follows:
html { scroll-behavior: smooth;}
The function of this style is to specify a scrolling behavior for elements with scroll bars, but it only takes effect when the user manually navigates or the CSSOM scrolling API triggers scrolling, and does not affect the scrolling caused by user behavior. Just when I was celebrating, I opened can i use and checked the compatibility:
Damn it, let’s just implement it with JS.
2. Use Window.scrollTo APIWe all know that window.scrollTo(x, y) realizes the function of scrolling to a certain position on the page by passing in the x and y axis coordinates in the document. In fact, this API can also pass in an option, which is an object. The left value corresponds to the x in the coordinates, the top corresponds to the y in the coordinates, and there is also a value of behavior, which allows you to customize the scrolling behavior. Then we implement scrolling like this To the top:
window.scrollTo({ left: 0, top: 0, behavior: 'smooth'})
It smells so good, done. A few days later, the product manager came to me with a 5-meter sword and said that the scrolling effect on Safari was strange and the physical examination was extremely poor. So I silently opened the MDN document and scrolled to the bottom:
Seeing this picture, although the API browser is almost supported, the option option hangs directly on Safari, so I opened stackoverflow again and summarized the ultimate solution.
3. Use requestAnimationFrameI often see the famous requestAnimationFrame, but I never have the chance to use it. This time I can try it out. We know that the function of requestAnimationFrame is to tell the browser to execute the incoming callback function before the next redraw. This behavior is automatically done by the browser for you. So we have the following code:
const scrollToTop = () => { let scrollTop = document.documentElement.scrollTo || document.body.scrollTop if (scrollTop > 0) { window.requestAnimationFrame(scrollTop) window.scrollTop(0, scrollTop - scrollTo / 8) }}
Done! ! ! Perfect! ! ! While excited, I turned on can i use to check the compatibility of requestAnimationFrame:
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.