jQuery 向下滚动页面时如何使导航栏更改颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27308425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:23:25  来源:igfitidea点击:

How to make navigation bar change color when you scroll down the page?

jquerynav

提问by user3218008

I would like the navigation bar to be transparent but when you scroll down the page it changes to color red for example.

我希望导航栏是透明的,但是当您向下滚动页面时,它会更改为例如红色。

<div class="nav">
      <div class="container">
       <div class="logo">
       <a href="#"><img src="RepublicSquare_logo.svg" style="height: 80px;"></a>
       </div>
        <div class="navMain">
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">About</a></li>
                <li><a href="#">Services</a></li>
                <li><a href="#">Portfolio</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </div>
      </div>
    </div>

回答by KaMZaTa

Something like this:

像这样的东西:

http://jsfiddle.net/qrhjdfmd/

http://jsfiddle.net/qrhjdfmd/

var a = $(".nav").offset().top;

$(document).scroll(function(){
    if($(this).scrollTop() > a)
    {   
       $('.nav').css({"background":"red"});
    } else {
       $('.nav').css({"background":"transparent"});
    }
});

回答by JKL

If anyone would be looking for a non-jquery solution (vanilla js), here it is:

如果有人正在寻找非 jquery 解决方案(vanilla js),这里是:

document.addEventListener("DOMContentLoaded", function () {
    var scrollStart = 0;
    var nav = document.querySelector(".nav");
    var offset = navbarElement.getBoundingClientRect();

    document.onscroll = function (e) {
        scrollStart = e.target.scrollingElement.scrollTop;
        if (scrollStart > offset.top) {
            nav.style.background-color, rgba(34,34,34,0.9);
        } else {
            nav.style.background-color = "transparent";
        }
    };
});

回答by C?ur

Solution by OP.

OP的解决方案。

Jquery

查询

$(document).ready(function(){       
   var scroll_start = 0;
   var startchange = $('.nav');
   var offset = startchange.offset();
   $(document).scroll(function() { 
      scroll_start = $(this).scrollTop();
      if(scroll_start > offset.top) {
          $('.nav').css('background-color', 'rgba(34,34,34,0.9)');
       } else {
          $('.nav').css('background-color', 'transparent');
       }
   });
});

CSS

CSS

.nav {
transition-duration: 1s;
}

This should make your navigation transparent and when you scroll it will change to rgba(34,34,34,0.9)

这应该使您的导航透明,当您滚动时,它将更改为 rgba(34,34,34,0.9)