JQuery在Y坐标后找到下一个元素?

时间:2016-08-16 20:20:24

标签: javascript jquery dom

假设我有一个div的页面,它们都具有相同的类,我正在使用.scroll通过.scrollTop监听和检索Y轴坐标。我想要做的是使用当前.scrollTop / Y位置之后的类名来定位下一个div。有没有办法将数值传递给JQuery选择器,说“找到下一个以'.my-class'开头的div,其开头Y位置大于当前Y位置”?

1 个答案:

答案 0 :(得分:0)

这应该是为你做的。代码在下面评论。

$(window).on('scroll', function(){
  // with '.my-class'
  $('.my-class').removeClass('active')
  // who's beginning Y position is greater than current Y position
  .filter(function(){
    return $(this).offset().top > $(window).scrollTop();
  }).first()
  // find the next div
  .next()
  // do stuff
  .addClass('active');
}).trigger('scroll');
body {background: #fff;}
.my-class {
  padding: 2em;
  border: 1px solid #eee;
  margin: 1em;
  border-radius: 1em;
}
.my-class.active {
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>
<div class="my-class">Test</div>