代码之家  ›  专栏  ›  技术社区  ›  P. Nick

滚动到一组div时获取其索引

  •  1
  • P. Nick  · 技术社区  · 6 年前

    <div class="row">Hello world 1</div>
    <div class="row">Hello world 2</div>
    <div class="row">Hello world 3</div>
    <div class="row">Hello world 4</div>
    <div class="row">Hello world 5</div>
    <div class="row">Hello world 6</div>
    

    所以当我滚动到第三行时,我希望它打印“You scrolled to div nr 3”。

    我试过这样的方法,但效果不如预期。

    $(window).on("scroll", function() {
        $.each($(".row"), function(index, item) {
            if($(item).offset().top + $(item).height() >= $(window).height()) {
                console.log("You scrolled to div nr: " + $(item).index());
            }
        });
    });
    

    如何才能做到这一点?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Dacre Denny    6 年前

    如果我正确理解您的要求,那么这将满足您基于滚动位置打印当前div(位于屏幕顶部)的要求:

    $(window).on("scroll", function() {
        $.each($(".row"), function(index, item) {
    
    
        var top = $(item).offset().top
        var offset = $(window).scrollTop() // Use window.scrollTop rather than height
    
        if(offset + $(item).height() >= top) {
          console.log("You scrolled to div nr: " + $(item).index());
        }
    
        });
    });
    

    主要的区别在于 $(window).scrollTop() 它根据窗口的当前滚动位置偏移“最上面可见的div”的选择

        2
  •  1
  •   Gianni    6 年前

    window.addEventListener("scroll", function() {
      var elementTarget = document.getElementById("section-2");
      if (window.scrollY > (elementTarget.offsetTop + elementTarget.offsetHeight)) {
      alert("You've scrolled past the second div");
    }
    });
    

    您可以在每个循环中动态地将第2部分更改为第2个。另外,当您输出div时,请确保在尝试运行scroll函数之前将单个数字放入类中。