滚动时更改背景颜色

时间:2014-07-18 10:08:21

标签: jquery html css css3

滚动时,如何将背景颜色更改为纯色?当用户平稳过渡时,必须触发颜色变化。

http://jsfiddle.net/6ranX/

<div class="sticky-nav">
</div>

.sticky-nav{
position: fixed;
width: 100%;
height: 60px;
background: rgba(0,0,0,0.4);
background: -moz-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%);
background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(0,0,0,0.4)), color-stop(100%, rgba(0,0,0,0)));
background: -webkit-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%);

3 个答案:

答案 0 :(得分:2)

使用jQuery,您可以在文档滚动中触发类更改,并根据CSS中的该类更改颜色,如下所示:

<强> DEMO

jQuery:

$(document).ready(function () {
    $(window).scroll(function(){
        $('.sticky-nav').addClass('scrolled');
    });
});

CSS:

.sticky-nav.scrolled{
    background: gold;
}

答案 1 :(得分:1)

只需创建两个CSS类。一个用于纯色背景,另一个用于渐变色。然后使用jQuery .scroll()事件侦听器在两个CSS类之间切换。

答案 2 :(得分:0)

看看this小提琴

在此代码中,您可以截取开始和结束滚动(使用jquery-throttle-debounce

如果scrool高于100px,则在滚动期间背景变为蓝色。

jquery的

$(window).scroll($.debounce( 250, true, function(){
    $('#scrollMsg').html('SCROLLING');
    var height = $(window).scrollTop();

    if(height  > 100) {
        $('p').addClass('linear');
    }

} ) );
$(window).scroll($.debounce( 250, function(){
    $('#scrollMsg').html('FINISH');
    $('p').removeClass('linear');
} ) );

CSS

#scrollMsg{
 position:fixed;
 color: red;
 font-size: 20px; 
    background-color: white!important;
    padding:20px;
}
p{
    background: rgba(0,0,0,0.4);
    background: -moz-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%);
    background: -webkit-gradient(left top, left bottom, color-stop(0%, rgba(0,0,0,0.4)), color-stop(100%, rgba(0,0,0,0)));
    background: -webkit-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%);
    background: -o-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%);
    background: -ms-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%);
    background: linear-gradient(to bottom, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#000000', endColorstr='#000000', GradientType=0 );
}
.linear{
    background-color:blue;
}