CSS Change Background Color at Certain Point

后端 未结 4 582
鱼传尺愫
鱼传尺愫 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:51

    If you only want something to happen when the element is in the viewport, you can find the top/bottom positions of the element and compare it to the scrolled distance and bottom of the window.

    $(window).on('resize scroll',function() {
      var $div = $('div'),
          $body = $('body'),
          st = $(this).scrollTop(),
          wh = $(this).height(),
          wb = st + wh,
          dh = $div.height(),
          dt = $div.offset().top,
          db = dh + dt;
      if (dt < wb && db > st) {
        $body.addClass('color');
      } else {
        $body.removeClass('color');
      }
    })
    section {
      height: 150vh;
    }
    div {
      background: black;
      height: 200px;
    }
    .color {
      background: red;
    }
    
    

提交回复
热议问题