簡體   English   中英

頁面滾動時更改標題背景顏色

[英]Change header background colour when page scrolls

我一直在尋找解決方案,但我無法讓它工作。

當用戶開始滾動頁面時,我希望我的頁眉從透明背景變為白色背景。

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;   
}
$(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規則,否則背景顏色不會改變

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM