Change font color on scroll based on a div

2020-06-29 02:58发布

I am currently coding a simple MENU button that is fixed in the top right of the screen.

With the text it is normally Black, but I want to be able to change the text to White when it is within a certain Div on a page so it is still visible on the dark background images.

I had set up two .CSS classes and tried to get them to switch on scroll but I cannot figure it out.

Anyone know how I can achieve this result?

HTML

  <div class="NavigationButton menu_white">
    MENU
  </div>

CSS

.NavigationButton {
 position: fixed;
 top: 5%;
 right: 5%;
 z-index: 99999;
 font-family: neuzeit-grotesk, sans-serif;
 font-weight: 700;
 color: inherit;
}

.menu_white {
 color: #fff;
}

.menu_black {
 color: #000;
}

(Not My Site) Example site: http://flavinsky.com/home/amaio

Just without the snap scroll

Thanks

2条回答
老娘就宠你
2楼-- · 2020-06-29 03:19

A possible solution is to get the offset of the div and the menu from the top of the page and apply your wanted changes once they intersect.

查看更多
看我几分像从前
3楼-- · 2020-06-29 03:25

You can use jQuery to get the scroll position and toggle the classes based on where the dark background element is. Here is an example

$(document).ready(function(){
    $(window).scroll(function(){
    var light_pos = $('#white_div').offset().top;
    var light_height = $('#white_div').height();
    var menu_pos = $('.NavigationButton').offset().top;
    var scroll = $(window).scrollTop();

    if(menu_pos > light_pos && menu_pos < (light_pos + light_height)) {
        $('.NavigationButton').addClass('menu_black');
      $('.NavigationButton').removeClass('menu_white');
    }
    else {
        $('.NavigationButton').removeClass('menu_black');
      $('.NavigationButton').addClass('menu_white');
    }

  })
})

and here is a working fiddle https://jsfiddle.net/atqkuwhs/

查看更多
登录 后发表回答