[英]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.