javascript - 滚动到特定 div 类时更改 div 颜色
问题描述
我在滚动时添加背景颜色时遇到问题。目前我的代码正在运行,但直到我滚动到 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>
解决方案
此外,为了扩展Spring 的答案,您也可以只使用.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>
推荐阅读
- powershell - 不带引号的 PowerShell 哈希表到 JSON
- php - PDO 版本属性从何而来?
- reactjs - 我应该在 React Hook 中为 CRUD 使用操作还是创建可重用函数
- android - 在 Android 范围内的 Firetore 中查询 GeoHashes
- javascript - 当我使用 DELETE 方法时,即使 id 不存在,我也会作为 JSON 响应获得成功
- java - 如何在java中找到char的ansi值?
- c++ - GetRawInputData 不适用于 x64 构建
- reactjs - 禁止用户从网站下载 SVG
- jekyll - 使用 Jekyll (GitHub Pages) 为每个子文件夹设置 BaseURL
- azure-data-explorer - 如何使用 KUSTO 提取两个请求之间的时间差