【问题标题】:Changing nav-bar color after scrolling?滚动后更改导航栏颜色?
【发布时间】:2014-07-05 12:57:03
【问题描述】:

如何设置没有背景颜色的导航栏?

在 div 之后向下滚动时,导航栏会获得新的背景颜色(导航栏应该固定在顶部,我在 Bootstrap 中使用navbar-fixed-top

我尝试了一些教程,但没有成功。

这是网站:http://attafothman.olympe.in/
我说的是顶部的黑色导航栏。

【问题讨论】:

  • 能否提供您自己尝试过的代码?
  • 您可能会与词缀组合并检查它是否是 jquery 页面的底部。然后是 if 语句,如果是底部,则更改导航栏的类。

标签: javascript jquery html css twitter-bootstrap


【解决方案1】:

这可以使用 jQuery 来完成。

这是fiddle的链接。

当窗口滚动时,比较窗口顶部和窗口高度之间的距离。当 if 语句为真时,背景颜色设置为透明。当您滚动回顶部时,颜色会变回白色。

$(document).ready(function(){
    $(window).scroll(function(){
        if($(window).scrollTop() > $(window).height()){
            $(".menu").css({"background-color":"transparent"});   
        }
        else{
            $(".menu").css({"background-color":"white"});
        }

    })
})

【讨论】:

  • 但是我如何指定滚动功能更改应该发生的高度......似乎我必须在它启动之前滚动一点情人。Gracias
【解决方案2】:

这是jsfiddle example。使用 Jquery 根据滚动像素位置更改背景颜色。

这是fiddle using bootstrap

$(document).ready(function(){       
   var scroll_start = 0;
   var startchange = $('#startchange');
   var offset = startchange.offset();
    if (startchange.length){
   $(document).scroll(function() { 
      scroll_start = $(this).scrollTop();
      if(scroll_start > offset.top) {
          $(".navbar-default").css('background-color', '#f0f0f0');
       } else {
          $('.navbar-default').css('background-color', 'transparent');
       }
   });
    }
});

【讨论】:

  • 嘿,这很好用,但是 scroll_start > 70 我不得不将 70 更改为 950 在其他显示器上尝试后,它的背景颜色变化的位置不同..
  • 让我尝试编辑小提琴以使用偏移量,我会在更改时发布链接
  • new js fiddle 这将允许您在 html 中使用 id,例如

    ,来设置更改高度而不是设置像素值
  • 奇怪!我在想这会解决它,但是当我更改导航器大小时,通过#startchange .. btw 后,背景颜色会发生变化。这可能是个问题?
  • 嗯...让我尝试在我的引导示例中实现它
【解决方案3】:
<script>
    $(document).ready(function(){
      $(window).scroll(function() { // check if scroll event happened
        if ($(document).scrollTop() > 50) { // check if user scrolled more than 50 from top of the browser window
          $(".navbar-fixed-top").css("background-color", "#f8f8f8"); // if yes, then change the color of class "navbar-fixed-top" to white (#f8f8f8)
        } else {
          $(".navbar-fixed-top").css("background-color", "transparent"); // if not, change it back to transparent
        }
      });
    });
</script>

【讨论】:

  • 欢迎来到 Stack Overflow。您应该考虑添加更多解释。仅代码的答案往往会被否决。
【解决方案4】:

这是一个简单的纯javascript

var myNav = document.getElementById('mynav');
window.onscroll = function () { 
    "use strict";
    if (document.body.scrollTop >= 200 ) {
        myNav.classList.add("nav-colored");
        myNav.classList.remove("nav-transparent");
    } 
    else {
        myNav.classList.add("nav-transparent");
        myNav.classList.remove("nav-colored");
    }
};

在某些 chrome 版本中存在以下错误:

document.body.scrollTop

所以你可以添加这样的条件:

 if (document.body.scrollTop >= 200 || document.documentElement.scrollTop >= 200 )

确定你必须有 2 个班级

.nav-colored { background-color:#000; }
.nav-transparent { background-color:transparent;}

【讨论】:

  • 这是一个很好的纯 JS 解决方案,但 else 部分应该是:.add("nav-transparent");.remove("nav-colored");
【解决方案5】:
window.addEventListener('scroll', function (e) {
        var nav = document.getElementById('nav');
        if (document.documentElement.scrollTop || document.body.scrollTop > window.innerHeight) {
                nav.classList.add('nav-colored');
                nav.classList.remove('nav-transparent');
            } else {
                nav.classList.add('nav-transparent');
                nav.classList.remove('nav-colored');
            }
    });

使用事件监听器的最佳方法。特别是对于 Firefox 浏览器,请查看此文档 Scroll-linked effects 和 Firefox 不再支持 document.body.scrollTop 和替代使用 document.documentElement.scrollTop。这是来自Yahya Essam的完整答案

【讨论】:

    【解决方案6】:

    这是在窗口滚动后更改导航栏颜色的最简单方法:

    在头部添加follow JS:

    $(function () {
      $(document).scroll(function () {
        var $nav = $(".navbar-fixed-top");
        $nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
      });
    });
    

    还有这个 CSS 代码

    .navbar-fixed-top.scrolled {
      background-color: #fff !important;
      transition: background-color 200ms linear;
    }
    

    当滚动超过导航栏的高度时,固定导航栏的背景颜色将变为白色。

    见关注JsFiddle

    【讨论】:

    • 如何使用这个功能来改变导航栏点击展开时的颜色?
    • 嗨!我只是想为将来来到这里的任何人添加:不要忘记添加“.navbar-fixed-top{transition:background-color 200ms linear;}”这样当你向上滚动时没有 insta-backgroundcolor
    • 您好!我已经喜欢这种方法一段时间了,但是最新的 Bootstrap 5 不知何故“滚动”类在滚动后没有应用于导航栏,这可能是因为在 v5 中如何调用 jQuery。关于如何调整的任何想法?谢谢!
    • 哇,这个解决方案简直是天才……如此简单且有效。谢谢。
    【解决方案7】:

    上述答案略有不同,但使用 Vanilla JS:

    var nav = document.querySelector('nav'); // Identify target
    
    window.addEventListener('scroll', function(event) { // To listen for event
        event.preventDefault();
    
        if (window.scrollY <= 150) { // Just an example
            nav.style.backgroundColor = '#000'; // or default color
        } else {
            nav.style.backgroundColor = 'transparent';
        }
    });
    

    【讨论】:

      【解决方案8】:
      1. 所以我使用 querySelector 来获取导航栏
      2. 我在窗口中添加了一个滚动事件来跟踪 scrollY 属性
      3. 我检查它是否高于 50,然后将活动类添加到导航栏,否则,如果它已经包含它,我只需将其删除,我很确定条件可以更加精选和简化。

      我发了this codepen来帮你!

      const navbar = document.querySelector('#nav')
      
      window.addEventListener('scroll', function(e) {
        const lastPosition = window.scrollY
        if (lastPosition > 50 ) {
          navbar.classList.add('active')
        } else if (navbar.classList.contains('active')) {
          navbar.classList.remove('active')
        } else {
          navbar.classList.remove('active')
        }
      })
      

      【讨论】:

      • 欢迎来到 StackOverflow!你能提供更多信息吗?喜欢这段代码的作用以及它如何帮助解决问题?
      • 1- 所以我使用 querySelector 来获取导航栏 2- 我在窗口中添加了一个滚动事件来跟踪 scrollY 属性 3- 我检查它是否高于 50 然后我添加了 @987654323 @class 到导航栏,否则如果它已经包含它,我只需将其删除,我很确定条件可以更加规整和简化。
      • 谢谢,但请将其添加到您的答案中,这样会更有帮助
      【解决方案9】:

      我使用 Underscore 附带的 WordPress。所以当你注册你的主题脚本时,你会使用'jquery'和'underscore'作为依赖数组的句柄。如果您不使用 WordPress,请确保在脚本之前加载 jQuery 框架和 Underscore。

      代码笔:https://codepen.io/carasmo/pen/ZmQQYy

      制作这个演示(记住它需要 jQuery 和 Underscore)。

      HTML:

      <header class="site-header">
        <div class="logo">
        </div>
        <nav>navigation</nav>
      </header>
      
      <article>
        Content with a forced height for scrolling.  Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling. Content with a forced height for scrolling
      </article>
      

      CSS:

      body,
      html {
          margin: 0;
          padding: 0;
          font: 100%/180% sans-serif;
          background: #eee;
      }
      
      html {
          -webkit-box-sizing: border-box;
          -moz-box-sizing: border-box;
          box-sizing: border-box;
      }
      
      *,
      *::before,
      *::after {
          box-sizing: inherit;
      }
      
      article {
          height: 2000px;
          padding: 5%;
          background: #fff;
          margin: 2% auto;
          max-width: 900px;
          box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.10);
      }
      
      
      .site-header {
          background: #fff;
          padding: 20px 5%;
          box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.23);
          transition: all .5s ease-in-out;
          -web-kit-position: sticky;
          position: sticky;
          top: 0;
          display: -webkit-box;
          display: -ms-flexbox;
          display: flex;
          -webkit-box-orient: horizontal;
          -webkit-box-direction: normal;
          -ms-flex-direction: row;
          flex-direction: row;
          -webkit-box-align: center;
          -ms-flex-align: center;
          align-items: center;
          -webkit-box-pack: center;
          -ms-flex-pack: center;
          justify-content: center;
      
      }
      
      .logo {
          background-image: url('the-path-to-the-logo.svg');
          background-repeat: no-repeat;
          background-position: center center;
          width: 200px;
          height: 60px;
          background-size: contain;
          transition: width .5s ease-in-out, height .5s ease-in-out;
      }
      
      .site-header nav {
          text-align: right;
          -webkit-box-flex: 1;
          -ms-flex-positive: 1;
          flex-grow: 1;
          -ms-flex-preferred-size: 0;
          flex-basis: 0;
      }
      
      .site-header.is-scrolling {
          opacity: .8;
          background: tomato;
          padding: 10px 5%;
      }
      
      .site-header.is-scrolling .logo {
          height: 40px;
          width: 100px;
      }
      

      jQuery:

      ( function( window, $, undefined ) {
      
          'use strict';
      
          ////////////// Begin jQuery and grab the $ ////////////////////////////////////////
      
          $(document).ready(function() {
      
            function is_scrolling() {
      
              var $element = $('.site-header'),
                  $nav_height = $element.outerHeight( true );
      
              if ($(this).scrollTop() >= $nav_height ) { //if scrolling is equal to or greater than the nav height add a class
      
                $element.addClass( 'is-scrolling');
      
              } else { //is back at the top again, remove the class
      
                $element.removeClass( 'is-scrolling');
              }
      
            }//end is_scrolling();
      
          $(window).scroll(_.throttle(is_scrolling, 200));
      
      
        }); //* end ready
      
      
      })(this, jQuery);
      

      【讨论】:

        【解决方案10】:

        $(window).on('activate.bs.scrollspy', function (e,obj) {
        
          if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
            return;
          }
          
          var isBGLight = $(obj.relatedTarget).hasClass('nav_white');
          var isBGDark = $(obj.relatedTarget).hasClass('nav_blue');
          $('.menu').removeClass('nav_white');
          $('.menu').removeClass('nav_blue');
          if(isBGDark)
          {
            $('.menu').addClass('nav_white');
          }else if(isBGLight)
          {
            $('.menu').addClass('nav_blue');
          }
          /*var isScrolled = $(document).scrollTop() > 1;
            $('.menu').toggleClass('scrolled', isScrolled);
            $(".demos").toggleClass("demo");
            $(".demos").toggleClass("demo1");
          var posicionActual = $(document).scrollTop();
          $.each($('.nav_transparent'),function(){
            if ($(this).position().top < posicionActual){
              $("nav.menu").removeClass("nav_white");
              $("nav.menu").removeClass("nav_blue");
              $("nav.menu").addClass("nav_transparent");
              $(".demos").removeClass("demo");
              $(".demos").addClass("demo1");
              $(".cls").removeClass("cls2");
              $(".cls").addClass("cls1");
              $(".cl").removeClass("cl2");
              $(".cl").addClass("cl1");
              $(".hamb-bottom").css({"background-color": "#fff"});
              $(".hamb-middle").css({"background-color": "#fff"});
              $(".hamb-top").css({"background-color": "#fff"});
            }
          });
          $.each($('.nav_blue'),function(){
            if ($(this).position().top <= posicionActual){
              $("nav.menu").removeClass("nav_transparent");
              $("nav.menu").removeClass("nav_white");
              $("nav.menu").addClass("nav_blue");
              $(".demos").removeClass("demo1");
              $(".demos").addClass("demo");
              $(".cls").removeClass("cls2");
              $(".cls").addClass("cls1");
              $(".cl").removeClass("cl2");
              $(".cl").addClass("cl1");
              $(".hamb-bottom").css({"background-color": "#fff"});
              $(".hamb-middle").css({"background-color": "#fff"});
              $(".hamb-top").css({"background-color": "#fff"});
            }
          });
          $.each($('.nav_white'),function(){
            if ($(this).position().top <= posicionActual){
              $("nav.menu").removeClass("nav_blue");
              $("nav.menu").removeClass("nav_transparent");
              $("nav.menu").addClass("nav_white");
              $(".demos").removeClass("demo");
              $(".demos").addClass("demo1");
              $(".cls").removeClass("cls1");
              $(".cls").addClass("cls2");
              $(".cl").removeClass("cl1");
              $(".cl").addClass("cl2");
              $(".hamb-bottom").css({"background-color": "#4285f4"});
              $(".hamb-middle").css({"background-color": "#4285f4"});
              $(".hamb-top").css({"background-color": "#4285f4"});
            }
          });*/
        });
        $(window).on("scroll", function(){
          if($(document).scrollTop() < 10)
            {
              $('.nav').removeClass('nav_white');
              $('.nav').removeClass('nav_blue');
              $('.nav').removeClass('nav_transparent');
              $('.nav').addClass('nav_transparent');
          }
        });

        解决方案,也许

        【讨论】:

          【解决方案11】:

          我最近所做的与上面的一些示例略有不同,所以我想分享一下,尽管很晚!

          首先是 HTML,注意标题中只有一个类:

          <body>
          
          <header class="GreyHeader">
          </header>
          
          
          </body>
          

          还有 CSS:

          body {
          height: 3000px;
          }
          
          .GreyHeader{
          height: 200px; 
          background-color: rgba(107,107,107,0.66);
          position: fixed;
          top:200;
          width: 100%;
          
          }
          
          .FireBrickRed {
          height: 100px;
          background-color: #b22222;
          position: fixed;
          top:200;
          width: 100%;
          }
          
          .transition {
            -webkit-transition: height 2s; /* For Safari 3.1 to 6.0 */
            transition: height 2s;
          }
          

          html 仅使用 .greyHeader 类,但在 CSS 中我创建了另一个类,以便在滚动从顶部到达某个点时调用:

          $(function() {
              var header = $(".GreyHeader");
              $(window).scroll(function() {    
                  var scroll = $(window).scrollTop();
          
                  if (scroll >= 500) {
                      header.removeClass('GreyHeader').addClass("FireBrickRed ");
                      header.addClass("transition");
                  } else {
                      header.removeClass("FireBrickRed ").addClass('GreyHeader');
                      header.addClass("transition");
                  }
              });
          });
          

          检查这个小提琴:https://jsfiddle.net/29y64L7d/1/

          【讨论】:

            【解决方案12】:

            今天我遇到了同样的问题,如何将导航栏背景颜色更改为滚动。我正在寻找一个只使用 CSS 的解决方案,没有 jquery,没有 bootstrap 也没有 javascript。但后来发现目前还不能仅使用 CSS(截至 2019 年 12 月)。并且必须选择,我会坚持使用核心技术——javascript而不是jquery或bootstrap,除非使用js比其他的复杂得多。但幸运的是不是。

            代码如下:
            - 它使用windowonscroll/scroll事件来触发事件监听器。
            - 在事件监听器中,使用windowpageYOffset/scrollY查看滚动状态。

            两者之间的浏览器支持似乎相同:
            - https://caniuse.com/#search=pageYOffset
            - https://caniuse.com/#search=scrollY

            var navbar = document.querySelector('nav')
            
            window.onscroll = function() {
            
              // pageYOffset or scrollY
              if (window.pageYOffset > 0) {
                navbar.classList.add('scrolled')
              } else {
                navbar.classList.remove('scrolled')
              }
            }
            body {
              margin: 0;
              padding: 0;
              background: url(https://occ-0-325-395.1.nflxso.net/dnm/api/v6/6AYY37jfdO6hpXcMjf9Yu5cnmO0/AAAABaKr-dQAdVTt7fuGCgzntgBBrFce2DMW72dF86eO7EnXbFZvzmX2TPnQAg3HwAsvt7ZnDnP0nwuHOtPwpWGGOE22fXq2.webp?r=847) top/contain no-repeat;
            }
            
            nav {
              position: -webkit-sticky;
              position: sticky;
              /* sticky or fixed are fine */
              position: fixed;
              top: 0;
              height: 69px;
              width: 100%;
              background: linear-gradient(to bottom, #000, #0003 70%,#0000); /* background when scroll is in the top */
              transition: background .5s; /* control how smooth the background changes */
            }
            
            nav.scrolled {
              background: #0a0a0a;
            }
            
            main {
              height: 200vh;
            }
            <nav></nav>
            <main></main>

            【讨论】:

              【解决方案13】:

              首先你在 nav div (exp: id="nav") 中创建一个名为 nav 的 id(可以随意更改) 然后在body标签完成的底部。您添加此代码

              <script>
                $(document).ready(function()
                $(window).scroll(function(){
                 var scroll = $(window).scrollTop();
                   if(scroll>50){
                    $("#nav").css("background", "#555");
                     }
                     else {
                    $("#nav").css("background", "transparent");
                     }
                    })
                 })
              </script>
              

              【讨论】:

                【解决方案14】:

                $(document).ready(function(){
                      $(window).scroll(function() {
                        if ($(document).scrollTop() >1290 ) { 
                          $(".navbar-fixed-top").css("background-color", "rgb(255, 160, 160)"); 
                        }else if ($(document).scrollTop() >850) { 
                            $(".navbar-fixed-top").css("background-color", "black"); 
                          }else if ($(document).scrollTop() >350) { 
                            $(".navbar-fixed-top").css("background-color", "rgba(47, 73, 158, 0.514)"); 
                          }
                         else {
                          $(".navbar-fixed-top").css("background-color", "red"); 
                        }
                      });
                    });
                @import url(https://fonts.googleapis.com/css?family=Roboto+Slab:400,700|Open+Sans);
                body {
                  font-family: "Roboto Slab", sans-serif;
                  position: relative;
                }
                
                h1,
                h2,
                h3,
                h4 {
                  font-family: "Open Sans", sans-serif;
                }
                
                .main {
                  padding-top: 50px;
                }
                
                #home {
                  padding-top: 20%;
                  background-image: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://s31.postimg.org/l5q32ptln/coffee_cup_mug_apple.jpg');
                  background-attachment: fixed;
                  background-repeat: no-repeat;
                  background-position: center center;
                  position: relative;
                  height: 100vh;
                }
                
                #home h2 {
                  color: white;
                  font-size: 4em;
                }
                
                #home h4 {
                  color: white;
                  font-size: 2em;
                }
                
                #home ul {
                  list-style-type: none;
                  text-align: center;
                }
                
                #home li {
                  padding-bottom: 12px;
                  padding-right: 12px;
                  display: inline;
                }
                
                #home li:last-child {
                  padding: 0;
                }
                
                @media (max-width: 710px) {
                  #home li {
                    display: block;
                  }
                }
                
                .img-style {
                  height: 200px;
                  width: 200px;
                  margin-top: 50px;
                }
                
                #about {
                  height: 100vh;
                  padding-top: 10%;
                  background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://s32.postimg.org/sm6o6617p/photo_1432821596592_e2c18b78144f.jpg');
                  background-attachment: fixed;
                  background-repeat: no-repeat;
                  background-position: center center;
                  position: relative;
                  color: white;
                }
                
                #about p,
                li {
                  font-size: 17px;
                }
                
                .navbar.color-yellow {
                  background-color: yellow;
                  height: 50px;
                  color: yellow;
                }
                
                .navbar.color-change {
                  background-color: #f45b69;
                  height: 50px;
                  color: rgba(255, 254, 255, 0.8);
                }
                
                #portfolio {
                  padding-top: 30px;
                  rgba(226,
                  226,
                  226,
                  1);
                  background: linear-gradient(to bottom, rgba(226, 226, 226, 1) 0%, rgba(209, 209, 209, 1) 25%, rgba(219, 219, 219, 1) 57%, rgba(254, 254, 254, 1) 100%);
                  height: 100vh;
                }
                
                #portfolio .block .portfolio-contant ul li {
                  float: left;
                  width: 32.22%;
                  overflow: hidden;
                  margin: 6px;
                  position: relative;
                }
                
                #portfolio .block .portfolio-contant ul li:hover .overly {
                  opacity: 1;
                }
                
                #portfolio .block .portfolio-contant ul li:hover .position-center {
                  position: absolute;
                  top: 50%;
                  -webkit-transform: translate(0%, -50%);
                  -moz-transform: translate(0%, -50%);
                  -ms-transform: translate(0%, -50%);
                  transform: translate(0%, -50%);
                }
                
                #portfolio .block .portfolio-contant ul li a {
                  display: block;
                  color: #fff;
                }
                
                #portfolio .block .portfolio-contant ul li a h2 {
                  font-size: 22px;
                  text-transform: uppercase;
                  letter-spacing: 1px;
                }
                
                #portfolio .block .portfolio-contant ul li a p {
                  font-size: 15px;
                }
                
                #portfolio .block .portfolio-contant ul li a span {
                  font-style: italic;
                  font-size: 13px;
                  color: #655E7A;
                }
                
                #portfolio .block .portfolio-contant ul img {
                  width: 100%;
                  height: auto;
                }
                
                #portfolio .block .portfolio-contant .overly {
                  position: absolute;
                  top: 0;
                  bottom: 0;
                  right: 0;
                  left: 0;
                  background: rgba(0, 0, 0, 0.9);
                  opacity: 0;
                  -webkit-transition: .3s all;
                  -o-transition: .3s all;
                  transition: .3s all;
                  text-align: center;
                }
                
                #portfolio .block .portfolio-contant .position-center {
                  position: absolute;
                  top: 50%;
                  left: 10%;
                  -webkit-transform: translate(0%, 50%);
                  -moz-transform: translate(0%, 50%);
                  -ms-transform: translate(0%, 50%);
                  transform: translate(0%, 50%);
                  -webkit-transition: .5s all;
                  -o-transition: .5s all;
                  transition: .5s all;
                }
                
                #contact {
                  height: 100vh;
                  padding-top: 10%;
                  background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://s32.postimg.org/ex6q1qxkl/pexels_photo.jpg");
                  background-attachment: fixed;
                  background-size: cover;
                  background-repeat: no-repeat;
                  background-position: center center;
                  position: relative;
                }
                
                #contact h3 {
                  color: white;
                }
                
                footer ul {
                  list-style-type: none;
                  text-align: center;
                }
                
                footer li {
                  display: inline;
                  padding-right: 10px;
                }
                
                footer li:last-child {
                  padding: 0;
                }
                
                footer p {
                  color: grey;
                  font-size: 11px;
                }
                <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
                <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
                <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
                <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
                <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
                <!DOCTYPE html>
                <html lang="en">
                
                <head>
                  <meta charset="UTF-8">
                  <meta name="viewport" content="width=device-width, initial-scale=1.0">
                  <meta http-equiv="X-UA-Compatible" content="ie=edge">
                  <title>Document</title>
                </head>
                
                <body>
                  <header>
                    <nav class="navbar navbar-default navbar-fixed-top" role="navigation">
                      <div class="container">
                        <div class="navbar-header">
                          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapse" aria-expanded="false">
                          <span class="sr-only">Toggle navigation</span>
                          <span class="icon-bar"></span>
                          <span class="icon-bar"></span>
                          <span class="icon-bar"></span>
                        </button>
                          <a class="navbar-brand" href="#featured">Portfolio</a>
                        </div>
                        <!-- navbar-header -->
                        <div class="collapse navbar-collapse" id="collapse">
                          <ul class="nav navbar-nav navbar-right">
                            <li class="active"><a href="#home">Home</a></li>
                            <li><a href="#about">About</a></li>
                            <li><a href="#portfolio">Portfolio</a></li>
                            <li><a href="#contact">Contact</a></li>
                          </ul>
                        </div>
                        <!-- collapse navbar-collapse -->
                
                      </div>
                      <!-- container -->
                    </nav>
                  </header>
                
                  <div class="main">
                    <div class="row " id="home" data-speed="2" data-type="background">
                      <div class="container">
                        <h2 class="text-center">Welcome to my portfolio</h2>
                        <h4 class="text-center">Where awesomeness is crafted</h4>
                        <hr>
                        <ul>
                          <li><a href="https://github.com/vamshi121" class="btn btn-primary"><i class="fa fa-github"></i> GitHub</a></li>
                          <li><a href="https://tn.linkedin.com/in/mannemvamshi" class="btn btn-primary"><i class="fa fa-linkedin"></i> LinkedIn</a></li>
                          <li><a href="https://freecodecamp.com/" class="btn btn-primary"><i class="fa fa-fire"></i> FreeCodeCamp</a></li>
                
                        </ul>
                      </div>
                      <!--container-->
                
                    </div>
                    <!--home-->
                    <div class="row" id="about" data-speed="2" data-type="background">
                      <div class="container">
                        <div class="row">
                          <div class="col-md-5 col-md-offset-1">
                            <h2>About me</h2>
                            <p>Courteous and Enthusiastic,I'm interested in IT and around in its globe. I began to be fascinated by web programming i.e, building websites and developing cross-platform apps.I'm always looking for new ventures where i can learn evolve and
                              expertise.
                              </marquee>
                          </div>
                          </p>
                          <p>My skills are:
                            <ul>
                              <li> Front-end : HTML5, CSS3 , jQuery, Bootstrap, AngularJS</li>
                              <li>Back-end: Ruby on Rails</li>
                              <li>Methodology: Agile, TDD</li>
                            </ul>
                          </p>
                        </div>
                        <!--col-md-5-->
                        <div class="col-md-4 col-md-offset-1">
                          <img class="img-circle img-style hidden-xs" src="https://www.triketech.site/images/log.png" />
                        </div>
                      </div>
                      <!--row-->
                    </div>
                    <!--container-->
                  </div>
                  <!--about-->
                  <div class="row" id="portfolio" data-speed="2" data-type="background">
                    <div class="container">
                      <h2 class="text-center">Portfolio projects</h2>
                      <div class="row">
                        <div class="col-md-12">
                          <div class="block">
                            <div class="portfolio-contant">
                              <ul id="portfolio-contant-active">
                                <li class="mix Branding">
                                  <a href="#">
                                    <img src="#" alt="">
                                    <div class="overly">
                                      <div class="position-center">
                                        <h2>Local Support</h2>
                
                
                                      </div>
                                    </div>
                                    <!--overly-->
                                  </a>
                                </li>
                              </ul>
                            </div>
                            <!--portfolio-contant-->
                          </div>
                          <!--block-->
                        </div>
                        <!--col-->
                      </div>
                      <!--row-->
                    </div>
                    <!--container-->
                  </div>
                  <!--portfolio-->
                  <div class="row" id="contact" data-speed="2" data-type="background">
                    <div class="container">
                      <div class="col-md-4 col-md-offset-1">
                        <h3>Contact me at:</h3>
                        <h3>thegreatvamshi@triketech.com</h3>
                      </div>
                      <!--col-md-4-->
                    </div>
                    <!--container-->
                  </div>
                  <!--contact-->
                  </div>
                  <!--main-->
                  <footer>
                    <ul>
                      <li><a href="#home">Home</a> </li>
                      <li><a href="#about">About</a> </li>
                      <li><a href="#portfolio">Portfolio</a> </li>
                      <li><a href="#contact">Contact</a> </li>
                    </ul>
                    <p class="text-center">Copyright &copy; - All Rights Reserved. </p>
                  </footer>
                
                </body>
                
                </html>
                <script> 
                    $(document).ready(function(){
                      $(window).scroll(function() {
                        if ($(document).scrollTop() >1920 ) { 
                          $(".navbar-fixed-top").css("background-color", "rgb(255, 160, 160)"); 
                        } else if ($(document).scrollTop() >1580) { 
                            $(".navbar-fixed-top").css("background-color", "black"); 
                        } else if ($(document).scrollTop() >620) { 
                            $(".navbar-fixed-top").css("background-color", "rgba(47, 73, 158, 0.514)"); 
                        } else {
                          $(".navbar-fixed-top").css("background-color", "transparent"); 
                        }
                      });
                    });
                </script>
                

                【讨论】:

                • 除了此代码示例之外,您还有什么可以添加到您的答案中的吗?带有解释的代码示例被认为更有帮助。
                【解决方案15】:

                我认为这个解决方案比旧答案更短更简单。 这是Js代码:

                const navbar = document.querySelector('.nav-fixed');
                window.onscroll = () => {
                    if (window.scrollY > 300) {
                        navbar.classList.add('nav-active');
                    } else {
                        navbar.classList.remove('nav-active');
                    }
                };
                

                还有我的 CSS:

                header.nav-fixed {
                    width: 100%;
                    position: fixed;
                    transition: 0.3s ease-in-out;
                }
                
                .nav-active {
                    background-color:#fff;
                    box-shadow: 5px -1px 12px -5px grey;
                }
                

                【讨论】:

                  【解决方案16】:

                  Intersection Observer API 怎么样?这避免了使用滚动事件的潜在迟缓。

                  HTML

                  <nav class="navbar-fixed-top">Navbar</nav>
                  <main>
                    <div class="content">Some content</div>
                  </main>
                  

                  CSS

                  .navbar-fixed-top--scrolled 更改导航栏背景颜色。当我们向下滚动时,当内容 div 不再 100% 可见时,它会添加到导航栏中。

                  .navbar-fixed-top {
                    position: sticky;
                    top: 0;
                    height: 60px;
                  }
                  
                  .navbar-fixed-top--scrolled {
                    /* change background-color to whatever you want */
                    background-color: grey;
                  }
                  

                  JS

                  创建观察者以确定内容 div 何时与浏览器视口完全相交。

                  回调函数被调用:

                  • 第一次要求观察者观察目标元素
                  • 当内容 div 不再完全可见时(由于阈值:1)
                  • 当内容 div 变得完全可见时(由于阈值:1)

                  isIntersecting 表示内容 div(目标元素)是否与观察者的根(默认浏览器视口)完全相交。

                  // callback function to be run whenever threshold is crossed in one direction or the other
                  const callback = (entries, observer) => {
                    const entry = entries[0];
                    
                    // toggle class depending on if content div intersects with viewport
                    const navBar = document.querySelector('.navbar-fixed-top');
                    navBar.classList.toggle('navbar-fixed-top--scrolled', !entry.isIntersecting);
                  }
                  
                  // options controls circumstances under which the observer's callback is invoked
                  const options = {
                    // no root provided - by default browser viewport used to check target visibility
                    // only detect if target element is fully visible or not
                    threshold: [1]
                  };
                  
                  const io = new IntersectionObserver(callback, options);
                  
                  // observe content div 
                  const target = document.querySelector('.content');
                  io.observe(target);
                  

                  IntersectionObserver 选项

                  当内容 div 开始移出屏幕时,导航栏当前会更改背景颜色。

                  如果我们希望在用户滚动时立即改变背景,我们可以使用 rootMargin 属性(上、右、下、左)并设置顶部导航栏高度为负值(在我们的例子中为 60 像素)。

                  const options = {
                    rootMargin: "-60px 0px 0px 0px",
                    threshold: [1]
                  };
                  

                  您可以在CodePen 上查看以上所有内容。 Kevin Powell 对此也有很好的解释 (Github & YouTube)。

                  【讨论】:

                    【解决方案17】:
                    1. 首先,您必须将 Jquery 包含到您的 HTML 文件或您正在使用的任何文件中。

                    2. 在文件的头部创建一个脚本代码空间并包含以下代码。

                    $(document).ready(function(){
                        $(window).scroll(function(){
                            if($(window).scrollTop() > 100){
                                $(".navbar").css({"background-color":"black"});   
                            }
                            else{
                                $(".navbar").css({"background-color":""});
                            }
                    
                        })
                    })
                    

                    这样,代码中的 ($(window).scrollTop() &gt; 100) 100 位于“px”中,因此您可以指定调用函数的高度。

                    这行代码$(".navbar").css({"background-color":"black"}); 用于替换 Nav 元素的类名。这只是直接访问 CSS,然后编辑 CSS。

                    HTML 代码如下

                    <header class="hero">
                            <nav class="navbar ">
                                <div class="container">
                                  <a class="navbar-brand" href="#"> 
                                    <img src="" alt=""> </a>
                                  <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                                    <span class="navbar-toggler-icon"></span>
                                  </button>
                                  <div class="collapse navbar-collapse" id="navbarSupportedContent">
                                    <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                                      <li class="nav-item">
                                        <a class="nav-link active" aria-current="page" href="#">Home</a>
                                      </li>
                                      <li class="nav-item">
                                        <a class="nav-link" href="#">TV shows</a>
                                      </li>
                                      <li class="nav-item">
                                        <a class="nav-link" href="#">Movies</a>
                                      </li>
                                      <li class="nav-item">
                                        <a class="nav-link" href="#">News and Popular</a>
                                      </li>
                                      <li class="nav-item">
                                        <a class="nav-link" href="#">My List</a>
                                      </li>
                                     
                                    </ul>
                                    
                                    
                                  </div>
                                </div>
                    </nav>
                    </header>
                    

                    【讨论】:

                      猜你喜欢
                      相关资源
                      最近更新 更多
                      热门标签