首页 > 解决方案 > 滚动到特定 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>

标签: javascripthtmljqueryscroll

解决方案


此外,为了扩展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>


推荐阅读