【问题标题】:Change div color when scrolling to a specific div class滚动到特定 div 类时更改 div 颜色
【发布时间】:2021-04-20 17:58:29
【问题描述】:
在滚动时添加背景颜色时遇到问题。目前我的代码正在运行,但直到我滚动到 div 的末尾才显示。这是background-overlay。
我想在滚动背景覆盖类时激活黑色类。另一个问题是当我滚动过去的 div 类没有删除。我的以下代码有什么遗漏吗?
https://jsfiddle.net/e6tfgs0a/2/
片段代码:
$(function() {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= $('.background-overlay').offset().top) { // check the offset top
$( ".background-overlay" ).addClass( "black" );
} else if(scroll >= $('.background-overlay').offset().top+$('.background-overlay').height()){ // check the scrollHeight
$( ".background-overlay" ).removeClass( "black" );
}
});
});
.full-height, .page {
height:500px;
}
.black {
background: #000000;
transition: background-color 1s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page">
</div>
<section class="full-height background-overlay" >
</section>
<div class="page">
</div>
【问题讨论】:
标签:
javascript
html
jquery
scroll
【解决方案1】:
此外,要扩展 Spring's answer,您也可以将 .scrollTop() 用于 background-overlay 部分:
$(function() {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= $('.background-overlay').scrollTop()) { // <-- changed this
$( ".background-overlay" ).addClass( "black" );
} else if(scroll >= $('.background-overlay').scrollTop()+$('.background-overlay').height()){ // check the scrollHeight
$( ".background-overlay" ).removeClass( "black" );
}
});
});
.full-height, .page {
height:500px;
}
.black {
background: #000000;
transition: background-color 1s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page">
</div>
<section class="full-height background-overlay" >
</section>
<div class="page">
</div>
【解决方案2】:
如果我理解您的问题,第一个条件检查将是您的 div 的 offsettop - height,第二个条件是条件错误(条件 iversion),
还将过渡添加到您 .background-overlay 而不是 .black 将在上下滚动时都有效果
$(function() {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var $divBlack = $('.background-overlay');
if (scroll >= $divBlack.offset().top - $divBlack.height()) { // check the offset top
$divBlack.addClass("black");
} else if (scroll <= $divBlack.offset().top + $divBlack.height()) { // check the scrollHeight
$divBlack.removeClass("black");
}
});
});
.full-height,
.page {
height: 500px;
border-bottom: 1px solid black;
}
.black {
background: #000000;
}
.background-overlay {
transition: background-color 2s ease;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page">
</div>
<section class="full-height background-overlay">
</section>
<div class="page">
</div>