Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use JavaScript to implement the return to the top button

Shulou Source: shulou.com Published: 2022-06-02 17:01:21 10月23日 Update

This article introduces the knowledge of "how to use JavaScript to achieve the return to the top button". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Train of thought:

First of all, the static style is designed. Here, fixed positioning is mainly used to fix it in a location at the bottom of the page.

.backtotop {position: fixed; bottom: 80px; right: 80px; width: 80px; height: 80px; background-color: # ccc; font-size: 20px; text-align: center; padding-top: 12px; box-sizing: border-box; cursor: pointer; color: # 000; / * hide button * / display: none;}

The second is the design logic: when the mouse clicks the "back to the top" button, it will return to the top with a fixed "speed" every 20 milliseconds, and after returning to the top, it will be cleared, otherwise it will automatically return to the top as long as the page is pulled down; two methods will be used here, one is setInterval, the other is clearInterval, the former is to set the timer, and the latter is to clear the timer.

It should be noted here that in order not to cause conflicts, it is necessary to "set the table and turn off" before setting the timer.

Finally, in order to increase the user's sense of experience, we need to design that if it is at the top, the "return to the top" button will be automatically hidden; if it is not at the top, the "return to the top" button will be displayed

Finally, let's take a look at the complete case:

Return

Top a {text-decoration: none;} body {height: 5000px;} .backtotop {position: fixed; bottom: 80px; right: 80px; width: 80px; height: 80px; background-color: # ccc; font-size: 20px; text-align: center; padding-top: 12px; box-sizing: border-box; cursor: pointer; color: # 000 / * hide the button * / display: none;} (function () {/ / get the element var backtotop = document.getElementById ('backtotop'); var timer; backtotop.onclick = function () {/ / set the table off first to prevent timer conflicts clearInterval (timer)) / / set timer timer = setInterval (function () {/ / change the scrollTop element value of the root element / / compatibility problem var top = document.documentElement.scrollTop | | document.body.scrollTop; top = top-80; document.documentElement.scrollTop = top; document.body.scrollTop = top; / / judge if (top)

Tags: Top buttons timers pages elements design content more case knowledge conflict utility learning next two location compatibility cycle dilemma reality Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information NVidia Linux Apple Shulou Technology