Detect when a div with fixed position crosses over another element

喜夏-厌秋 提交于 2019-12-02 09:51:36

You have to take the div heights in account.

There is two "moments" to caculate, the enter and the leave.

So when the bottom of the fixed div enters the top of the scrolled one...
And when the bottom of the scrolled one leaves the top of the fixed.

Here is an example to run:

$(window).scroll(function(){
  var fixed = $("div.fixed");
  
  var fixed_position = $("div.fixed").offset().top;
  var fixed_height = $("div.fixed").height();

  var toCross_position = $(".div-to-cross").offset().top;
  var toCross_height = $(".div-to-cross").height();

  if (fixed_position + fixed_height  < toCross_position) {
    fixed.removeClass('white');
  } else if (fixed_position > toCross_position + toCross_height) {
    fixed.removeClass('white');
  } else {
    fixed.addClass('white');
  }

});
.fixed{
  position:fixed;
  top:calc(50% - 50px);
  left:0;
  background-color:black;
  height:100px;
  width:100%;
}
.white{
  background-color:white;
}
.div-to-cross{
  height:100px;
  background-color:blue;
}

/* just for this demo */
.spacer{
  height:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="fixed"></div>
<div class="spacer"></div>
<div class="div-to-cross"></div>
<div class="spacer"></div>

Thank you. I modified it a bit so it works for multiple div-to-cross elements. I´m using it to change my fixed white burger menu when it overlaps a div with white background. Then it got another color until it leaves the white background div.

//Burger Scroll Change Color
$(window).scroll(function(){
    var fixed = $("div.fixed");

    var fixed_position = $("div.fixed").offset().top;
    var fixed_height = $("div.fixed").height();

    var addClass = false;
    $('.div-to-cross').each(function(){

        var toCross_position = $(this).offset().top;
        var toCross_height = $(this).height();

        if (fixed_position + fixed_height  < toCross_position) {
            //fixed.removeClass('white');
        } else if (fixed_position > toCross_position + toCross_height) {
            //fixed.removeClass('white');
        } else {
            addClass = true;
        }
    });
    if(addClass == true){
        fixed.addClass('change-color');
    }else{
        fixed.removeClass('change-color');
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!