[英]How to detect the scroll position of a `article` and add a class
我有四篇不同的文章,內容不同。 我所要做的就是當滾動位置到達需要添加活動類的文章的頂部位置時。 我試過沒有成功。 這是我到目前為止所嘗試的代碼。
HTML
<article></article>
<article></article>
<article></article>
<article></article>
CSS
article{
height: 800px;
background-color: gray;
}
article:nth-child(2){
background-color: blue;
}
article:nth-child(3){
background-color: pink;
}
article:last-child{
background-color: orange;
}
article.active{
background-color: red;
}
JQuery的
var scrollPosition = $('article').scrollTop();
$(window).scroll(function () {
if ($(window).scrollTop() == scrollPosition) {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
})
我建議使用.offset()來獲取元素的絕對位置。
這是一個例子:
$(window).scroll(function () {
$('article').each(function () {
var ArtOffsetTop = $(this).offset().top;
var ArtOffsetBottom = $(this).offset().top + $(this).height();
if (($(window).scrollTop() >= ArtOffsetTop) && ($(window).scrollTop() <= ArtOffsetBottom)) {
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
})
})
我添加了一個新變量ArtOffsetBottom
來檢測$(window).scrollTop()
是否位於文章的頂部和底部之間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.