[英]How do I trigger jQuery when an anchor reaches the top of the viewport?
I need to trigger a jQuery function on a div when an anchor reaches the top of the viewport. 当锚到达视口顶部时,我需要在div上触发jQuery函数。 There are a lot of posts on StackOverflow based on an element entering the viewport (ie the bottom of the viewport) see here for example.
基于进入视口(即视口底部 )的元素,StackOverflow上有很多帖子,例如,请参见此处 。
Is it possible to trigger jQuery for the .nav-down
element when the anchor #trigger
hits the top of the view port? 当锚点
#trigger
到达视口顶部时,是否可以为.nav-down
元素触发jQuery?
HTML: HTML:
<div class="spacer"></div>
<a href="#" id="trigger">ANCHOR</a>
<div class="nav-down"></div>
<div class="spacer"></div>
jS: jS:
function scroll_style() {
var window_top = $(window).scrollTop();
var div_top = $('#trigger').offset().top;
if (window_top > div_top){
$('.nav-down').css("background","green");
}
}
$(function() {
$(window).scroll(scroll_style);
scroll_style();
});
This jS/jSFiddle doesn't work as intended, but it'll give an idea of the thought process I have: 这个jS / jSFiddle并没有按预期工作,但是会给我一个思路:
https://jsfiddle.net/vanstone/s643m85b/14/ https://jsfiddle.net/vanstone/s643m85b/14/
Can anyone assist me with getting this to work? 谁能协助我使它生效?
You can try using the getBoundingClientRect()
to get the position of <a>
with respect to the viewport and then implement your logic. 您可以尝试使用
getBoundingClientRect()
获取<a>
相对于视口的位置,然后实现您的逻辑。
In the below example, I am checking for top < 10
to factor in the height of <a>
在下面的示例中,我正在检查
top < 10
以将<a>
的高度<a>
function scroll_style() { if ($('#trigger')[0].getBoundingClientRect().top < 10) { $('.nav-down').css("background", "green"); } else { $('.nav-down').css("background", "yellow"); } } $(function() { $(window).scroll(scroll_style); scroll_style(); });
.spacer { height: 700px; background: red; } .nav-down { height: 250px; width: 100%; background: blue; }
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <div class="spacer"></div> <a href="#" id="trigger">ANCHOR</a> <div class="nav-down"></div> <div class="spacer"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.