Have you noticed that whether you are browsing the website on a computer or a mobile phone, when we slide down the page, there will be a button in the lower right corner prompting the user to return directly to the top. Then you know how to use native JS to return the page Top effect? This article will share with you the pure JS code for clicking a button to return to the top. It has certain reference value and interested friends can refer to it.
Achieving the effect of clicking a button to return to the top of the page requires a lot of JavaScript knowledge, such as: function(), document.getElementById(), if function, etc. If you are not sure, you can refer to the PHP Chinese website Related articles, or visit JavaScript Video Tutorial.
Instance description: The user slides down the page. When the distance between the scroll bar and the top is greater than 20px, a "Return to Top" button appears. Click the button to return directly to the top and the button disappears. The specific code is as follows:
HTML part:
<button onclick="topFunction()" id="myBtn" title="回顶部">JS返回顶部</button> <div style="background-color:pink;color:white;padding:80px">向下滑动</div> <div style="background-color:lightgrey;padding:80px 30px 2500px">页面内容,此处省略一万字</div>
CSS part:
*{padding: 0;margin: 0;} #myBtn { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; border: none; outline: none; background-color: skyblue; color: white; cursor: pointer; padding: 15px; border-radius: 10px; } #myBtn:hover { background-color: plum; }
JavaScript part:
// 当网页向下滑动 20px 出现"返回顶部" 按钮 window.onscroll = function() {scrollFunction()}; function scrollFunction() {console.log(121); if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById("myBtn").style.display = "block"; } else { document.getElementById("myBtn").style.display = "none"; } } // 点击按钮,返回顶部 function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; }
The effect is as shown in the picture:
I have shared with you how to use native JavaScript to implement the code for clicking a button to return to the top of the page. The code is concise and the steps are detailed. Beginners can try it by themselves to see if your code can return to the top of the page. effect, I hope this article will be helpful to you!
For more related tutorials, please visit JavaScript Chinese Reference Manual
The above is the detailed content of Pure JS implements the code for clicking the button to return to the top of the page. For more information, please follow other related articles on the PHP Chinese website!