Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use JavaScript to implement the back Top Button

Shulou Source: shulou.com Published: 2022-06-02 17:00:31 10月13日 Update

This article focuses on "how to use JavaScript to achieve the return to the top button", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn "how to use JavaScript to achieve the return to the top button"!

1. Put up a shelf first

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 button * / / * display: none;*/} return

Top

two。 Logical part

When the mouse clicks the "return to the top" button, it will return to the top at a fixed "speed" every 50 milliseconds, and clear it after returning to the top, otherwise it will automatically return to the top as soon as the page is pulled down.

Two methods are 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

.backtotop {/ * hide the button * / display: none;} (function () {/ / 1. Get the element let oBackBtn = document.querySelector ("# backtotop"); / / 2. Listen to the scrolling of the web page _ window.onscroll = function () {/ / get the scrolling distance let offsetY = getPageScroll () .y; / / console.log (offsetY) / / determine whether the rollback button if (offsetY > = 200) {oBackBtn.style.display = "block";} else {oBackBtn.style.display = "none";}} let timerId = null; / / 3 needs to be displayed. Click oBackBtn.onclick = function () {/ / set the table off first to prevent timer conflicts clearInterval (timerId); / / set timer timerId = setInterval (function () {let begin = getPageScroll (). Y) / / current position let target = 0; / / Target location let step = (target-begin) * 0.3; begin + = step; / / determine whether to end if (Math.abs (Math.floor (step)

Tags: Top button timer location web page content direction method conflict learning monitoring practical deeper shelf two elements interest cycle practicality practical Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft MariaDB macOS Docker NVidia