简体   繁体   English

在滚动时显示元素(向上和向下) - 当页面为 static(不滚动)时隐藏元素

[英]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).当用户滚动页面(上下滚动)时,我想让计算机鼠标的 svg 图像出现在视口底部。 When the page is static (no scroll) I would like the element to be hidden.当页面为 static(无滚动)时,我希望隐藏该元素。 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?是否可以将此效果应用于 html 元件? Many thanks for your help in advance.非常感谢您提前提供的帮助。

This can be achieved by listening for the "scroll" event, window.addEventListener('scroll', someFunction) .这可以通过监听“滚动”事件window.addEventListener('scroll', someFunction)来实现。

We can show the div by changing its display style from "none" to "block" box.style.display = 'block' .我们可以通过将其显示样式从“none”更改为“block”来显示 div box.style.display = 'block'

And setting a timeout that, in five seconds, will call another function to hide the div again setTimeout(hideBox, 5000) .并设置一个超时,在五秒内,将调用另一个 function 再次隐藏 div 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/您可以在 Mozilla 文档中找到所有这些函数的定义和解释: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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