滚动下来时如何更改div背景颜色?

时间:2017-07-10 04:11:01

标签: javascript html css

向下滚动页面时如何更改div背景颜色。 示例:http://allencreativity.weebly.com/

2 个答案:

答案 0 :(得分:0)

考虑一下这个例子:

 $('body').bind('mousewheel', function(e){
      var elem = $('.divToChange');
      var hT = elem.offset().top,
          hH = elem.outerHeight(),
          wH = $(window).height(),
          wS = $(this).scrollTop();
            if(e.originalEvent.wheelDelta /120 > 0) {
               if(wS == hT){
                 elem.css('background-color', 'red');
               }
            }else{
               if (wS > (hT+hH-wH/2)){
                  elem.css('background-color', 'white');
               } 
            }
          });

答案 1 :(得分:0)

您可以使用Jquery。 $(document).scrollTop()返回的值等于$(document).height() - $(window).height()



$(document).ready(function(){
  $(window).scroll(function () {
    if($(document).scrollTop() > 50){
      $("#myDiv").css('background','red');
    }
    else{
      $("#myDiv").css('background','');
    }
  });
});

#myDiv{
  height:500px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="myDiv">
  This is my div
</div>
&#13;
&#13;
&#13;