检查视口中是否显示带有类的元素

时间:2017-08-03 14:39:18

标签: jquery

我正在尝试检测视口中当前是否显示某个类。我正在使用此answer(无法回复我的问题)。原帖使用的是ID而不是类,我已将其更改为检测名为.white-section的类,该类在页面上重复。

目前它只检测到第一个.white-section,如何在它们进入视口时检测它们?

$('#content').scroll(function() {
    var top_of_element = $(".white-section").offset().top;
    var bottom_of_element = $(".white-section").offset().top + $(".white-section").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).height();
    var top_of_screen = $(window).scrollTop();

    if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
         $('.header-container').addClass('.alt-menu');
    }
    else {
        $('.header-container').removeClass('.alt-menu');
    }
});

这是html的设置方式:

<div class="header-container"></div>

<div class="white-section"></div>
<div class="white-section"></div>
<div class="white-section"></div>
<div class="white-section"></div>
<div class="white-section"></div>

1 个答案:

答案 0 :(得分:1)

尝试以下内容。它循环遍历元素以尝试查找与条件匹配的任何元素,如果有的话,它会添加类。我还为解决方案添加了一些轻微的限制,并且还缓存了查找,以便滚动事件更快。

&#13;
&#13;
(function($) {
  var scrollingIsThrottled = false;
  var $allWhiteSections = $(".white-section");
  var $window = $(window);
  var $headerContainer = $('.header-container');

  $('#content').scroll(function() {
    if (!scrollingIsThrottled) {
      scrollingIsThrottled = true;

      var $whiteSpaceMatchingExpression = $allWhiteSections.filter(function() {
        var $this = $(this);
        var top_of_element = $this.offset().top;
        var bottom_of_element = $this.offset().top + $this.outerHeight();
        var bottom_of_screen = $window.scrollTop() + $window.height();
        var top_of_screen = $window.scrollTop();

        return ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element));
      });
      
      if ($whiteSpaceMatchingExpression.length) {
        $headerContainer.addClass('alt-menu');
      } else {
        $headerContainer.removeClass('alt-menu');
      }
      
      scrollingIsThrottled = false;
    }
  });
}(jQuery));
&#13;
&#13;
&#13;

相关问题