页面滚动时更改标题背景颜色

时间:2015-02-01 19:10:38

标签: jquery html css colortransform

我一直在寻找解决方案,但我无法让它发挥作用。

当用户开始滚动页面时,我希望我的页面标题从透明背景更改为白色背景。

HTML代码是:

<div class="header">
    <div class="topbar"></div>
    <div class="sitelogo"></div>
    <nav id="navigation">
        <ul>
            <li id="twitter"><a href="http://www.twitter.com/iamdanmorris"><em>Twitter</em></a></li>
            <li><a href="#contact">Contact</a></li>
            <li><a href="#blog">Blog</a></li>
            <li><a href="#">Portfolio</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Home</a></li>
        </ul>
    </nav>
    <div style="clear:both;"></div>
</div>

CSS代码是:

.header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    padding: 0;
    z-index: 10000;
    -webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
    -moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
    box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
    transition: all 0.2s ease-in-out;
    height: auto;
    background-color:transparent;   
}

1 个答案:

答案 0 :(得分:19)

$(window).on("scroll", function() {
    if($(window).scrollTop() > 50) {
        $(".header").addClass("active");
    } else {
        //remove the background property so it comes transparent again (defined in your css)
       $(".header").removeClass("active");
    }
});

小提琴:http://jsfiddle.net/634d6vgq/2/

如果用户从顶部滚动了超过50个像素,这会将background-color: #fff添加到元素

这将添加一个“活动”类,以便您可以在css中设置样式(更易于维护)

编辑

$(function() {
    $(window).on("scroll", function() {
        if($(window).scrollTop() > 50) {
            $(".header").addClass("active");
        } else {
            //remove the background property so it comes transparent again (defined in your css)
           $(".header").removeClass("active");
        }
    });
});

你的css:

.active { background-color: #fff}

确保您还添加此css规则,或者背景颜色不会改变

相关问题