简体   繁体   中英

Show element on scroll (both up and down) - hide element when page is static (not scrolling)

I would like to make a svg image of a computer mouse appear at the bottom of the viewport when user scrolls the page (both up and down scrolling). When the page is static (no scroll) I would like the element to be hidden. It is the same effect as the scrollbar on the right in the browser. Is it possible to apply this effect to a html element? Many thanks for your help in advance.

This can be achieved by listening for the "scroll" event, window.addEventListener('scroll', someFunction) .

We can show the div by changing its display style from "none" to "block" box.style.display = 'block' .

And setting a timeout that, in five seconds, will call another function to hide the div again setTimeout(hideBox, 5000) .

You can find the definition and explanation for all of these functions in the Mozilla docs: https://developer.mozilla.org/en-US/

I've also included a simple but working example:

 (function () { let timeoutHandle = 0; const box = document.getElementById("box"); // add the scroll event window.addEventListener("scroll", (e) => { box.style.display = "block"; clearTimeout(timeoutHandle); // call function to hide box after 5 seconds timeoutHandle = setTimeout(hideBox, 5000); }); // hides box by setting display to 'none' hideBox = () => { box.style.display = "none"; }; })();
 #box { position: fixed; bottom: 2px; right: 2px; line-height: 95px; height: 100px; width: 100px; border: 3px solid red; text-align: center; display: none; } #box p { display: inline-block; vertical-align: middle; }
 <div> <a id="top"> <.-- hidden anchor --></a> <p> This is just some sample text.</p> <p> You should pay attention to the tiny box at the bottom right corner. It appears when you scroll.</p> <p> Now we add a very long image to make scrolling possible:</p> <img src="https.//i.pinimg.com/564x/75/b7/8a/75b78ae86b6f81ed20f41f57e2a3a7f2.jpg"> </div> <div id="box"> <a href="#top">jump top</a> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM