【问题标题】:Need help making navbar change from a transparent background to a solid background on scroll需要帮助将导航栏从透明背景更改为滚动时的纯色背景
【发布时间】:2019-08-25 15:19:52
【问题描述】:

当我尝试使用 js 时,它在 50px 后没有改变,它只是保持相同的透明度..

这是我的代码: https://codepen.io/greenmistweb/pen/WNeppeE

我试图找到 youtube 教程,但它们都不想工作

$(function() {
   $(window).scroll(function () {
      if ($(this).scrollTop() > 50) {
         $(‘topnav’).addClass(‘changeColor’)
      }
      if ($(this).scrollTop() < 50) {
         $(‘topnav’).removeClass(‘changeColor’)
      }
   });
});

认为这会在滚动超过 50 像素后转到 CSS 中的 .changeColor ,但它什么也没做。

【问题讨论】:

    标签: jquery html css scroll navbar


    【解决方案1】:

    我稍微修改了您的代码,您似乎遇到了一些问题:

    1. 您没有导入 jquery
    2. 您的 javascript 代码可能已被复制和粘贴,导致 ' 出现错误;
    3. 您试图引用“topnav”而不是使用类名 .topnav;

    我已调整您的位置检查以在更改颜色时使用您的 about-me div 作为参考,因为使用静态 50px 值可能会在未来带来一些问题;

    $(function() {
       var aboutMePosition = $('.about-me').position().top;
       $(window).scroll(function () {
         var currentPosition = $(this).scrollTop();
          if (currentPosition >= aboutMePosition) {
             $('.topnav').addClass('changeColor')
          } else {
             $('.topnav').removeClass('changeColor')
          }
       });
    });
    @font-face {
    	font-family: 'Poiret One';
    	font-style: normal;
    	src: url(Fonts/PoiretOne-Regular.ttf);
    }
    
    @font-face {
    	font-family: 'Darker Grotesque';
    	src: url(Fonts/DarkerGrotesque-Light.ttf);
    }
    
    @font-face {
    	font-family: 'Pathway Gothic';
    	src: url(Fonts/PathwayGothicOne-Regular.ttf);
    }
    
    
    /* Add a black background color to the top navigation */
    .topnav {
      background-color: transparent;
      overflow: hidden;
    	position: fixed;
    	top: 0;
    	width: 100%;
    	z-index: 1000;
    	font-family: 'Darker Grotesque', sans-serif;
    	transition: .5s;
    }
    
    /* Style the links inside the navigation bar */
    .topnav a {
      float: left;
      display: block;
      color: #f2f2f2;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
      font-size: 17px;
    }
    
    /* Change the color of links on hover */
    .topnav a:hover {
      background-color: #ddd;
      color: black;
    }
    
    /* Add an active class to highlight the current page */
    .topnav a.active {
      color: white;
    }
    
    /* Hide the link that should open and close the topnav on small screens */
    .topnav .icon {
      display: none;
    }
    
    /* When the screen is less than 600 pixels wide, hide all links, except for the first one ("Home"). Show the link that contains should open and close the topnav (.icon) */
    @media screen and (max-width: 600px) {
      .topnav a:not(:first-child) {display: none;}
      .topnav a.icon {
        float: right;
        display: block;
      }
    }
    
    /* The "responsive" class is added to the topnav with JavaScript when the user clicks on the icon. This class makes the topnav look good on small screens (display the links vertically instead of horizontally) */
    @media screen and (max-width: 600px) {
      .topnav.responsive {position: relative;}
      .topnav.responsive a.icon {
        position: absolute;
        right: 0;
        top: 0;
      }
      .topnav.responsive a {
        float: none;
        display: block;
        text-align: left;
      }
    }
    
    .card {
    	background: white;
    	margin-bottom: 2em;
    }
    
    .card a {
    	color: black;
    	text-decoration: none;
    }
    
    .card a:hover {
    	box-shadow: 3px 3px 8px hsl(0, 0%, 80%);
    }
    
    .card-content {
    	padding: 1.4em;
    }
    
    .card-content h2 {
    	margin-top: 0;
    	margin-bottom: .5em;
    	font-weight: bold;
    }
    
    .card-content p {
    	font-size: 80%;
    }
    
    /* Flexbox stuff */
    
    .cards {
       display: flex;
       flex-wrap: wrap;
       justify-content: space-between;
    }
    
    .card {
    	flex: 0 1 24%;
    }
    
    @media screen and (max-width: 600px) {
      .services {
        margin:20px
      }
    }
    
    @media screen and (max-width:600px) {
      .service-list {
        flex: 0 1 50%;
      }
    }
    
    
    body, html {
        height: 100%;
    }
    
    /* The hero image */
    .hero-image {
      /* Use "linear-gradient" to add a darken background effect to the image (photographer.jpg). This will make the text easier to read */
      background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("first-img.jpg");
    
      /* Set a specific height */
      height: 650px;
    
      /* Position and center the image to scale nicely on all screens */
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
      position: relative;
    	margin: -10px;
    }
    
    /* Place text in the middle of the image */
    .hero-text {
      text-align: center;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: white;
    	font-family: 'Poiret One';
    }
    
    .who-i-am {
    	display: flex;
    	width: 600px;
    	justify-content: center;
    	align-items: center;
    }
    
    .description {
    	flex: 1;
    	margin: 50px;
    }
    
    .about-me {
    	display: flex;
    	flex-direction: row;
    	flex-wrap: wrap;
    }
    
    .centered-link a {
      float: none;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    
    .serv-desc {
    	display: flex;
    	flex-direction: row;
    	flex-wrap: wrap;
    }
    
    .service {
    	flex-basis: 100%;
    	text-align: center;
    	margin: 30px;
    	font-family: 'Pathway Gothic';
    }
    
    @media screen and (min-width:600px) {
    	.service {
    		flex: 1;
    	}
    }
    
    h2 {
    	text-align: center;
    	font-family: 'Pathway Gothic';
    }
    
    .changeColor {
      background: black;
    }
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="icon" type="image/png" href="dwaynes_logo_no_words.png">
        <link rel="stylesheet" href="style.css">
        <title>greenMist Web Solutions</title>
      </head>
      <body>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    
        <div class="topnav">
          <a href="#home" class="active">Home</a>
          <a href="#news">News</a>
          <a href="#contact">Contact</a>
          <a href="#about">About</a>
          <div class="centered-link">
            <a class="brand" href="#home">greenMist Web Solutions</a>
          </div>
          <a href="javascript:void(0);" class="icon" onclick="myFunction()">
            <i class="fa fa-bars"></i>
          </a>
        </div>
    
        <div class="hero-image">
          <div class="hero-text">
            <h1>I am Dwayne Rill, Jr.</h1>
            <p></p>
            <button></button>
          </div>
        </div>
    
        <div class="about-me">
          <div class="who-i-am">
            <h1>About Me</h1>
          </div>
          <div class="description">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
            incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
            ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
            in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
            non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            <br>
            <br>
            This is some more info
            <br>
            <br>
            and some more
            <br>
            <br>
            and another one!
          </div>
        </div>
    
        <div class="services">
          <h2>Services</h2>
          <div class="serv-desc">
            <div class="service">
              <div id="frontEnd">
              <h3>Front-End Development</h3>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
                dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
                Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
                mollit anim id est laborum.</p>
              </div>
            </div>
    
            <div class="service">
              <div id="responive">
              <h3>Responsive Development</h3>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
                dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
                Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
                mollit anim id est laborum.</p>
              </div>
            </div>
    
            <div class="service">
              <div id="migration">
              <h3>Host Migration</h3>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
                incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
                exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
                dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
                Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
                mollit anim id est laborum.</p>
              </div>
            </div>
          </div>
        </div>
    
        <div class="pricing options">
          words
        </div>
    
        <div class="contact me">
          words
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      </body>
    </html>

    【讨论】:

    • 这个答案与我发布的答案有何不同?
    • 谢谢!当谈到 javascript 时,我是一个非常非常非常的初学者。我正在尝试自学,但我无法解决,所以我复制并粘贴了一些代码来尝试找出我做错了什么,但它也没有奏效。感谢您帮助我!
    【解决方案2】:

    您的代码发生了几件事:

    1. 您的单引号是花哨的引号。它们需要替换为普通的单引号。
    2. $('topnav') 应该是 $('.topnav') - 请注意,您没有选择类 topnav 的元素。您的代码正在寻找具有该名称的元素。
    3. 你没有在任何地方包含 jQuery,所以这个$ 对代码没有任何意义。

    这是一个工作示例:

    (function($) {
      $(window).scroll(function() {
        if ($(this).scrollTop() > 50) {
          $('.topnav').addClass('changeColor')
        }
        if ($(this).scrollTop() < 50) {
          $('.topnav').removeClass('changeColor')
        }
      });
    })(jQuery);
    @font-face {
      font-family: 'Poiret One';
      font-style: normal;
      src: url(Fonts/PoiretOne-Regular.ttf);
    }
    
    @font-face {
      font-family: 'Darker Grotesque';
      src: url(Fonts/DarkerGrotesque-Light.ttf);
    }
    
    @font-face {
      font-family: 'Pathway Gothic';
      src: url(Fonts/PathwayGothicOne-Regular.ttf);
    }
    
    
    /* Add a black background color to the top navigation */
    
    .topnav {
      background-color: transparent;
      overflow: hidden;
      position: fixed;
      top: 0;
      width: 100%;
      z-index: 1000;
      font-family: 'Darker Grotesque', sans-serif;
      transition: .5s;
    }
    
    
    /* Style the links inside the navigation bar */
    
    .topnav a {
      float: left;
      display: block;
      color: #f2f2f2;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
      font-size: 17px;
    }
    
    
    /* Change the color of links on hover */
    
    .topnav a:hover {
      background-color: #ddd;
      color: black;
    }
    
    
    /* Add an active class to highlight the current page */
    
    .topnav a.active {
      color: white;
    }
    
    
    /* Hide the link that should open and close the topnav on small screens */
    
    .topnav .icon {
      display: none;
    }
    
    
    /* When the screen is less than 600 pixels wide, hide all links, except for the first one ("Home"). Show the link that contains should open and close the topnav (.icon) */
    
    @media screen and (max-width: 600px) {
      .topnav a:not(:first-child) {
        display: none;
      }
      .topnav a.icon {
        float: right;
        display: block;
      }
    }
    
    
    /* The "responsive" class is added to the topnav with JavaScript when the user clicks on the icon. This class makes the topnav look good on small screens (display the links vertically instead of horizontally) */
    
    @media screen and (max-width: 600px) {
      .topnav.responsive {
        position: relative;
      }
      .topnav.responsive a.icon {
        position: absolute;
        right: 0;
        top: 0;
      }
      .topnav.responsive a {
        float: none;
        display: block;
        text-align: left;
      }
    }
    
    .card {
      background: white;
      margin-bottom: 2em;
    }
    
    .card a {
      color: black;
      text-decoration: none;
    }
    
    .card a:hover {
      box-shadow: 3px 3px 8px hsl(0, 0%, 80%);
    }
    
    .card-content {
      padding: 1.4em;
    }
    
    .card-content h2 {
      margin-top: 0;
      margin-bottom: .5em;
      font-weight: bold;
    }
    
    .card-content p {
      font-size: 80%;
    }
    
    
    /* Flexbox stuff */
    
    .cards {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
    }
    
    .card {
      flex: 0 1 24%;
    }
    
    @media screen and (max-width: 600px) {
      .services {
        margin: 20px
      }
    }
    
    @media screen and (max-width:600px) {
      .service-list {
        flex: 0 1 50%;
      }
    }
    
    body,
    html {
      height: 100%;
    }
    
    
    /* The hero image */
    
    .hero-image {
      /* Use "linear-gradient" to add a darken background effect to the image (photographer.jpg). This will make the text easier to read */
      background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("first-img.jpg");
      /* Set a specific height */
      height: 650px;
      /* Position and center the image to scale nicely on all screens */
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
      position: relative;
      margin: -10px;
    }
    
    
    /* Place text in the middle of the image */
    
    .hero-text {
      text-align: center;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: white;
      font-family: 'Poiret One';
    }
    
    .who-i-am {
      display: flex;
      width: 600px;
      justify-content: center;
      align-items: center;
    }
    
    .description {
      flex: 1;
      margin: 50px;
    }
    
    .about-me {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    
    .centered-link a {
      float: none;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    
    .serv-desc {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    
    .service {
      flex-basis: 100%;
      text-align: center;
      margin: 30px;
      font-family: 'Pathway Gothic';
    }
    
    @media screen and (min-width:600px) {
      .service {
        flex: 1;
      }
    }
    
    h2 {
      text-align: center;
      font-family: 'Pathway Gothic';
    }
    
    .changeColor {
      background: black;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
    
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link rel="icon" type="image/png" href="dwaynes_logo_no_words.png">
      <link rel="stylesheet" href="style.css">
      <title>greenMist Web Solutions</title>
    </head>
    
    <body>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    
      <div class="topnav">
        <a href="#home" class="active">Home</a>
        <a href="#news">News</a>
        <a href="#contact">Contact</a>
        <a href="#about">About</a>
        <div class="centered-link">
          <a class="brand" href="#home">greenMist Web Solutions</a>
        </div>
        <a href="javascript:void(0);" class="icon" onclick="myFunction()">
          <i class="fa fa-bars"></i>
        </a>
      </div>
    
      <div class="hero-image">
        <div class="hero-text">
          <h1>I am Dwayne Rill, Jr.</h1>
          <p></p>
          <button></button>
        </div>
      </div>
    
      <div class="about-me">
        <div class="who-i-am">
          <h1>About Me</h1>
        </div>
        <div class="description">
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
          in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
          <br>
          <br> This is some more info
          <br>
          <br> and some more
          <br>
          <br> and another one!
        </div>
      </div>
    
      <div class="services">
        <h2>Services</h2>
        <div class="serv-desc">
          <div class="service">
            <div id="frontEnd">
              <h3>Front-End Development</h3>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
                irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
          </div>
    
          <div class="service">
            <div id="responive">
              <h3>Responsive Development</h3>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
                irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
          </div>
    
          <div class="service">
            <div id="migration">
              <h3>Host Migration</h3>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
                irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
            </div>
          </div>
        </div>
      </div>
    
      <div class="pricing options">
        words
      </div>
    
      <div class="contact me">
        words
      </div>
    </body>
    
    </html>

    这是一个可以玩的代码笔: https://codepen.io/chrislafrombois/pen/aboJJdx

    【讨论】:

    • 也谢谢你!感谢您也抽出时间来回答这个问题!
    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 2017-04-30
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    相关资源
    最近更新 更多