如何在滚动时顺利更改css属性?

时间:2015-04-17 12:42:30

标签: jquery

我有一个任务 - 我的导航块有背景属性background: rgba(0,0,0, 0); 我需要在滚动时平滑地将其不透明度从0更改为1,这没问题,但动画结束(我的意思是背景的不透明度达到1的那一刻)是某个块的底部边框

所以这是我的HTML代码

<header>
    <nav>...</nav>
</header>

header具有灵活的高度。 nav的高度为100px。所以当scrollTop值为:

时,我需要导航的背景不透明度达到1
$('header').height() - $(nav).height();

https://jsfiddle.net/zzvns9hy/7/

1 个答案:

答案 0 :(得分:0)

您可以执行类似

的操作

HTML

<header>
    <nav></nav>
</header>

CSS

nav {
    width:100px;
    height:100px;
}

SCRIPT

$(window).scroll(function() {
    // what is the position of nav from the top of the document
    var NavTop = Math.floor( $(document).scrollTop() - $('nav').offset().top );
    // From 0 to 1, how much is nav scrolled
    var NavScroll = NavTop / $('nav').height(); 

    $('nav').css('background-color','rgba(255,0,0,'+NavScroll+')');
});

http://jsfiddle.net/an50e93p/