首页 > 解决方案 > 视口内最长的元素

问题描述

我正在尝试将“活动”类设置为页面上最可见的元素。使用此代码,我能够将页面上显示的元素设置为“活动”类。

我正在为我的无限滚动项目这样做。如果我可以为我的目标元素提供活动类,我可以更改社交媒体共享过程的页面 url 和标题。

    $.fn.isInViewport = function() {
  var elementTop = $(this).offset().top;
  var elementBottom = elementTop + $(this).outerHeight();

  var viewportTop = $(window).scrollTop();
  var viewportBottom = viewportTop + $(window).height();

  return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).on('resize scroll', function() {
  $('article').each(function() {
    if ($(this).isInViewport()) {
      $(this).addClass('active');
    } else {
      $(this).removeClass('active');
    }
  });
});
<article>
    <h1>Title 1</h1>
    <p>Text...
    ..
    .</p>
</article>
<article>
    <h1>Title 2</h1>
    <p>Text2...
    ..
    .</p>
</article>
<article>
    <h1>Title 2</h1>
    <p>Text2...
    ..
    .</p>
</article>
   
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

标签: jquerycssajax

解决方案


不确定什么是最明显的,但您可以使用指示是否找到可见元素的标志,重置所有元素并将活动类设置为您找到的第一个。

$.fn.isInViewport = function() {
  var elementTop = $(this).offset().top;
  var elementBottom = elementTop + $(this).outerHeight();

  var viewportTop = $(window).scrollTop();
  var viewportBottom = viewportTop + $(window).height();
  return elementBottom > viewportTop && elementTop < viewportBottom && elementTop > viewportTop;
};


$(window).on('load resize scroll', function() {
  var activeFound = false;
  $('article').each(function() {
    if (!activeFound) {
      if ($(this).isInViewport()) {
        $("article.active").removeClass("active");
        $(this).addClass('active');
        activeFound = true;
      }
    }
  });
});
.active {
  color: blue;
}
<article>
  <h1>Title 1</h1>
  <p>Text... .. .
  </p>
</article>
<article>
  <h1>Title 2</h1>
  <p>Text2... .. .
  </p>
</article>
<article>
  <h1>Title 2</h1>
  <p>Text2... .. .
  </p>
</article>
<article>
  <h1>Title 1</h1>
  <p>Text... .. .
  </p>
</article>
<article>
  <h1>Title 2</h1>
  <p>Text2... .. .
  </p>
</article>
<article>
  <h1>Title 2</h1>
  <p>Text2... .. .
  </p>
</article>
<article>
  <h1>Title 1</h1>
  <p>Text... .. .
  </p>
</article>
<article>
  <h1>Title 2</h1>
  <p>Text2... .. .
  </p>
</article>
<article>
  <h1>Title 2</h1>
  <p>Text2... .. .
  </p>
</article>
<article>
  <h1>Title 1</h1>
  <p>Text... .. .
  </p>
</article>
<article>
  <h1>Title 2</h1>
  <p>Text2... .. .
  </p>
</article>
<article>
  <h1>Title 2</h1>
  <p>Text2... .. .
  </p>
</article>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


推荐阅读