CSS Change Background Color at Certain Point

后端 未结 4 577
鱼传尺愫
鱼传尺愫 2021-01-27 17:18

I would like the background of the entire site to change from white to black when a certain element comes into view. So when you scroll by the element the background transitions

4条回答
  •  清酒与你
    2021-01-27 17:59

    Using the scroll event you can calculate the offset of the h1 (or whatever element) which gets the current coordinates of the element. the wScroll variable gets the current vertical position of the scroll bar in this case the top of the window. On the condition you check if the scrollbar is greater or equal to the element you which to target and subtract that from the window height (if you wish to change the background once the element is on the screen change the 1.2 to 1) add a transition to the body for the animation. Check the demo scroll down. Sorry if its not well explained, excuse my writing.

    $(window).scroll(function(){
      var wScroll = $(this).scrollTop();
    
    if(wScroll >= $('h1').offset().top - ($(window).height() / 1.2 ) ){
      $("body").css("background-color", "black");
    }else{
      $("body").css("background-color", "white");
    }
    
    });
    body{
      transition: background-color 0.3s ease-in-out;
    }
    p{height: 1000px;}
    h1{
    height: 400px;
      color: white;
    }
    
    

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit autem reprehenderit, nesciunt maxime incidunt facilis, aliquid vel deserunt, provident voluptatibus magni, nam. Doloribus sint ipsa nihil fuga, ad minima reiciendis.

    Change to Black

提交回复
热议问题