jquery - 视口内最长的元素
问题描述
我正在尝试将“活动”类设置为页面上最可见的元素。使用此代码,我能够将页面上显示的元素设置为“活动”类。
我正在为我的无限滚动项目这样做。如果我可以为我的目标元素提供活动类,我可以更改社交媒体共享过程的页面 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>
解决方案
不确定什么是最明显的,但您可以使用指示是否找到可见元素的标志,重置所有元素并将活动类设置为您找到的第一个。
$.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>
推荐阅读
- css - 引导网格列在 sm 和 xs 设备上未按预期工作
- ruby-on-rails - 没有路线匹配 [POST] "/sessions/user" 与设计
- react-native - 在 Reactnative 中自动获取当前位置
- php - 如何使用php在字符串中传递数组索引值?
- amazon-web-services - 在 IOT 上托管服务器并从 Internet 访问,无需在路由器上进行端口转发
- sql-server - 如何使用以下查询进行批量更新
- html - 在 webview android studio 中显示包含阿拉伯字符的 html 文件
- ios - 在 Xcode 项目中添加 Carthage 的最快方法
- hadoop - 有没有办法使用 webhdfs REST API 检查文件是否存在?
- ios - Iap 购买 - 无需自动续订订阅的试用版