Jquery在滚动时检测屏幕上可见的块

Ara*_*yan 0 jquery scroll dynamic visible

大家好我有一些问题,如果不是很难请帮忙.

如果我有一些div块的数量

<div class="main">
      <div class="box block1"></div>
      <div class="box block2"></div>
      <div class="box block3"></div>
      <div class="box block4"></div>
</div> 
Run Code Online (Sandbox Code Playgroud)

好了,现在当你在屏幕上滚动和阻止可见时,我需要在该块中做一些事情我可以用jquery每次滚动检测滚动顶部并用块偏移顶部检查它但这是不好的解决方案,因为我需要写很多"如果"检查它并且当我修复了块的数量时它起作用但我需要它会动态地工作.我找到一些插件,但我不想使用插件.我是一些基本的简单脚本,我可以在其他网站上更改或添加或修改

如果你有时间的话,请帮忙

这是我的HTML

我在我的投资组合页面做了一些事情,但它不是动态的,我写错了代码:)

滚动时,您可以在菜单上看到它,如果可见块,我将活动类添加到菜单

投资组合

Man*_*noz 5

试试这个

function isVisible( row, container ){
    
    var elementTop = $(row).offset().top,
        elementHeight = $(row).height(),
        containerTop = container.scrollTop(),
        containerHeight = container.height();
    
    return ((((elementTop - containerTop) + elementHeight) > 0) && ((elementTop - containerTop) < containerHeight));
}
$(window).scroll(function(){
  $('.main div').each(function(){
      if(isVisible($(this), $(window))){
      console.log($(this).attr('class')+" is visible");
      };  
  });
});
Run Code Online (Sandbox Code Playgroud)
.main .box {
        position: relative;
        width: 100%;
    }
    .main .block1 {
        background: red;
        height: 800px;
    }
    .main .block2 {
        background: green;
        height: 600px;
    }
    .main .block3 {
        background: yellow;
        height: 900px;
    }
    .main .block4 {
        background: orange;
        height: 1000px;
    }
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
          <div class="box block1"></div>
          <div class="box block2"></div>
          <div class="box block3"></div>
          <div class="box block4"></div>
    </div>
Run Code Online (Sandbox Code Playgroud)

在控制台上,您将注意到只显示块元素的可见部分!

默认情况下,您可以通过删除滚动事件来获取显示块的一部分.