简体   繁体   English

当一个部分接触到带有 Vanilla JS 的视口顶部时,如何触发一个功能?

[英]How can I trigger a function when a section touches the top of the viewport with Vanilla JS?

I basically want the browser to trigger a function when a section touches the top of the viewport as the user scrolls and I'm not really sure how to do this with Vanilla JS.我基本上希望浏览器在用户滚动时某个部分触及视口顶部时触发一个功能,但我不确定如何使用 Vanilla JS 执行此操作。

I've found some jQuery alternatives, but I'm just trying to figure out how Javascript works at the moment, so I'm not exactly sure where to begin or what to google for that matter.我找到了一些 jQuery 替代品,但我只是想弄清楚 Javascript 目前是如何工作的,所以我不确定从哪里开始或在谷歌上搜索什么。

The following example creates a page with a single div inside.以下示例创建一个页面,其中包含一个 div。 The scroll event handler uses Element.getBoundingClientRect() in order to get the div's position relative to the viewport and logs a msg to the console when the div is at or above the top edge of the viewport.滚动事件处理程序使用Element.getBoundingClientRect()来获取 div 相对于视口的位置,并在 div 位于或高于视口的顶部边缘时将 msg 记录到控制台。

 var handlerFired; window.addEventListener('scroll', function(e){ var containerTop = document.querySelector('.container').getBoundingClientRect().top; if (containerTop <= 0) { if (!handlerFired) { handlerFired = 1; console.log('container at top of viewport or above'); } } if (containerTop > 0) { handlerFired = 0; } });
 body{ height:2000px; } .container{ width:300px; height:200px; border:5px solid red; position: absolute; top: 100px; }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class='container'> <p>scroll window ...</p> </div> </body> </html>

暂无
暂无

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

相关问题 当用户将元素滚动到视口中时触发函数– Vanilla JavaScript - Trigger a function when the user scrolls the element into the viewport – Vanilla JavaScript 当锚点到达视口顶部时,如何触发jQuery? - How do I trigger jQuery when an anchor reaches the top of the viewport? 如果元素在视口中停留X倍的时间,如何触发函数? - How can I trigger a function if an element is in the viewport for X amount of time? 当顶部边框触及视口顶部时获取 div 的数据 - get data of a div when its top border touches the top of viewport 如果部分在视口中,则向 div 添加/删除类(vanilla JS) - Add/remove class to div if section is in viewport (vanilla JS) 在Vanilla JS的视口中切换CSS动画 - CSS animations to toggle when in viewport with vanilla JS 当球接触顶部边界时,如何添加“游戏结束”的警告框? - How can I add alert box that says “game over” when the ball touches the top border? 在香草JS中,如何根据滚动条是否位于顶部来从元素中添加或删除类? - In vanilla JS, how can I add or remove a class from an element based on whether the scroll is at the top? 当用户单击jQueryUI单选按钮时,如何停止浏览器视口移至页面顶部? - How can I stop the browser viewport moving to the top of the page when the user clicks on a jQueryUI radio button? 在移动视口中时,如何阻止bootstrap 4导航栏粘在页面顶部? - How can I stop the bootstrap 4 navbar from sticking to the top of the page when in mobile viewport?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM