I have been working on front-end projects recently, and many projects have the requirements to return to the top. Below I will write my js code to make a record of it for easier search in the future.
I found that the animation effect from fast to slow and the function of pulling down the scroll bar to stop scrolling at any time. I referred to the relevant courses on imooc, and finally implemented the JS code as follows:
//Trigger window.onload = function(){var btn = document.getElementById('btn');var timer = null;var isTop = true;//Get the page viewing area height var clientHeight = document.documentElement.clientHeight;//Trigger window.onscroll = function() {//Show back to top button var osTop = document.documentElement.scrollTop || document.body.scrollTop;if (osTop >= clientHeight) {btn.style.display = "block";} else {btn.style.display = "none";};//In the process back to the top, the user scrolls the scrollbar and stops the timer if (!isTop) {clearInterval(timer);};isTop = false;};btn.onclick = function() {//Set timer timer = setInterval(function(){//Get the scrollbar's height from the top var osTop = document.documentElement.scrollTop || document.body.scrollTop;var ispeed = Math.floor(-osTop / 7);document.documentElement.scrollTop = document.body.scrollTop = osTop+ispeed;//Add to the top, clear the timer if (osTop == 0) {clearInterval(timer);};isTop = true;},30);};};The above content is the animation code based on JavaScript based implementation back to the top of the page introduced by the editor. The code is simple and easy to understand. There are no too many comments attached to you. If you find any questions during the reference process, please leave me a message. The editor will reply to you in time!