change div color after scrolling 15% down with jqu

2019-09-22 08:45发布

问题:

I have this jquery code below which makes a div scroll. But I would also like it to change the div color to #32200F when is down 15% from the top.THen return to the original barckground when it is less than 15% from the top.

<script type="text/javascript">
        $().ready(function() {
                var $scrollingDiv = $("#navbar");

                $(window).scroll(function(){            
                        $scrollingDiv
                                .stop()
                                .animate({"marginTop": ($(window).scrollTop() + 0) + "px"}, "slow" );
                });
        });
</script>

Here is the CSS code of my original background.I can make it a class to make it easier:

#navbar {
     /* Fallback for web browsers that don't support RGBa */
     background-color: rgb(0, 0, 0);
     background-color: rgba(50,32,15,0.5);     
     /* For IE 5.5 - 7*/
     filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#4c32200F, endColorstr=#4f32200F);
     /* For IE 8*/
     -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#4c32200F, endColorstr=#4f32200F)";
}

回答1:

Try:

$(document).ready(function () {
   var $scrollingDiv = $("#navbar");

   $(window).scroll(function () {
       $scrollingDiv.stop()
           .animate({
           "marginTop": ($(window).scrollTop() + 0) + "px"
       }, "slow");
       $scrollingDiv.css("background-color", (($(window).scrollTop() / $(document).height()) > 0.15) ? "orange" : "");
     });
});

Demo



回答2:

<script type="text/javascript">
    $().ready(function() {
            var $scrollingDiv = $("#navbar");

            $(window).scroll(function(){            
                    $scrollingDiv
                            .stop()
                            .animate({"marginTop": ($(window).scrollTop() + 0)+ "px"},"slow");
                           $(".yourdiv").css('background-color', 'blue');
            });
    });