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

给你一囗甜甜゛ 提交于 2019-12-21 04:52:26

问题


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>

回答1:


Something like this:

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"});
    }
});



回答2:


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

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";
        }
    };
});



回答3:


Solution by 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

.nav {
transition-duration: 1s;
}

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



来源:https://stackoverflow.com/questions/27308425/how-to-make-navigation-bar-change-color-when-you-scroll-down-the-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!