jquery 检测重叠多个部分

jquery detect overlap multiple sections

我试图让我的固定导航在与我网站的不同部分重叠时改变颜色。 很像这个网站的导航:http://andpizza.com/

我的 html 存在 div 和部分。

<nav>
  <ul>
    <li class="work">Work</li>
    <li class="about">About</li>
    <li class="contact">Contact</li>
</nav>

<div id="red">
</div>

<section id="green">
</section>

<div id="blue">
</div>

<section id="yellow">
</section>

对于 JS,我使用在 github 上找到的 overlaps library

这个jquery我自己加的:

$(document).scroll(function() {

    var contactColl = $('ul li.contact').overlaps('section');
    $('ul li.contact')[contactColl.hits.length? 'addClass' : 'removeClass']('white');

    var aboutColl = $('ul li.about').overlaps('section');
    $('ul li.about')[aboutColl.hits.length? 'addClass' : 'removeClass']('white');

    var workColl = $('ul li.work').overlaps('section');
    $('ul li.work')[workColl.hits.length? 'addClass' : 'removeClass']('white');

});

或查看here on Codepen.

它非常适合第一部分。但它忽略了第二部分。我知道它会选择它遇到的第一部分,但我不知道如何让它适用于其他部分

我试过像这样分别命名这些部分:

var contactColl = $('ul li.contact').overlaps('#green, #yellow');

var contactColl = $('ul li.contact').overlaps('#green');
$('ul li.contact')[contactColl.hits.length? 'addClass' : 'removeClass']('white');

var contactColl2 = $('ul li.contact').overlaps('#yellow');
$('ul li.contact')[contactColl2.hits.length? 'addClass' : 'removeClass']('white');

这破坏了一切。

谁能帮我解决这个问题?

Overlaps 插件只处理一个目标重叠的对象。只是像这样的小修复:

$.fn.overlaps = function(objs) {
    var elems = {targets: [], hits:[]};
    this.each(function() {
        var bounds = $(this).offset();
        bounds.right = bounds.left + $(this).outerWidth();
        bounds.bottom = bounds.top + $(this).outerHeight();

        $(objs).each(function(){
          var obj = this;
          var compare = $(obj).offset();             
          compare.right = compare.left + $(obj).outerWidth();
          compare.bottom = compare.top + $(obj).outerHeight();

          if (!(compare.right < bounds.left ||
                compare.left > bounds.right ||
                compare.bottom < bounds.top ||
                compare.top > bounds.bottom)
             ) {
              elems.targets.push(this);
              elems.hits.push(obj);
          }
        });
    });

    return elems;
};

}(jQuery));

遍历对象集合 $(objs).each 而不是只获取其中的第一个 - 将解决这个问题。

Working demo