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

我一直在寻找一个解决方案,但我不能让它工作.

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

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.25);
    -moz-Box-shadow: 0 1px 5px rgba(0,0.25);
    Box-shadow: 0 1px 5px rgba(0,0.25);
    transition: all 0.2s ease-in-out;
    height: auto;
    background-color:transparent;   
}

解决方法

$(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个像素,这将向元素添加背景颜色:#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规则,或者背景颜色不会更改

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...