首页 > 解决方案 > 为什么 jQuery .scroll() 方法不能与 .addClass() 方法一起使用

问题描述

我正在尝试添加一个名为.nav-colorif window is scrolled 大于或等于 50px with jQuery ( jQuery version 3.6.0) 的类。为此,我创建了一个.nav-color类并尝试#navigation使用 jQuery.addClass()方法将其添加到其中,但不知何故它不起作用。

我的 jQuery 代码:

$(document).ready(function() {
            $(body).scroll(function() {
                if ($(body).scroll() > 20) {
                    $("#navigation").addClass("nav-color");   
                }
                else {
                    $("#navigation").removeClass("nav-color");
                }
            });
        });

为什么会这样?为什么代码不起作用?

这是我的完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="./images/favicon.ico">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css" integrity="sha384-SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk" crossorigin="anonymous">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: sans-serif;
            text-decoration: none;
            list-style: none;
        }
        header {
            background: linear-gradient(rgba(45, 44, 48, 0.753), rgba(45, 44, 48, 0.753)), url(./images/bg-masthead.jpg);
            height: 100vh;
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
            color: white;
            font-weight: bold;
        }
        .navbar-brand {
            font-size: 20px;
        }
        .navbar {
            position: fixed;
            width: 100%;
            top: 0;
            left: 0;
        }
        #header-texts {
            height: 90vh;
            align-items: center;
            margin-top: 60px;
            height: 90vh;
        }
        #header-texts-1 {
            font-size: 55px;
        }
        #header-texts-2 {
            font-size: 20px;
            font-weight: normal;
        }
        #header-btn {
            background: #f24516;
            color: white;
            padding: 15px 20px;
            border-radius: 30px;
            letter-spacing: 0.8px;
        }
        #s-5:hover {
            border-bottom: 1px solid #f24516;
        }
        .nav-color {
            background-color: #ffffff;
            color: black;
        }
        /* ========================= Responsive ========================= */
        @media (max-width: 540px) {
            #header-texts-1 {
                font-size: 30px;
            }
            #header-texts-2 {
                font-size: 16px;
            }
        }
        @media (min-width: 992px) {
            .container {
                width: 100vw !important;
            }
            .navbar-expand-lg {
                background: transparent !important;
            }
            a {
                color: white !important;
            }
        }
    </style>
    <title>Creative</title>
</head>
<body>
    <header>
        <div class="container">
            <div class="row">
                <div class="col">
                    <nav class="navbar navbar-expand-lg navbar-light bg-light" id="navigation">
                        <div class="container-fluid">
                            <a class="navbar-brand ms-lg-5" href="#">Start Bootstrap</a>
                            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                            <span class="navbar-toggler-icon"></span>
                            </button>
                            <div class="collapse navbar-collapse justify-content-end" id="navbarNavAltMarkup">
                                <div class="navbar-nav me-lg-5" id="nav-items">
                                    <a class="nav-link active" aria-current="page" href="#">Home</a>
                                    <a class="nav-link" href="#">About</a>
                                    <a class="nav-link" href="#">Services</a>
                                    <a class="nav-link" href="#">Protfolio</a>
                                    <a class="nav-link" href="#">Contact</a>
                                </div>
                            </div>
                        </div>
                    </nav>
                </div>
            </div>
            <div class="row text-center" id="header-texts">
                <div class="col">
                    <p id="header-texts-1">YOUR FAVORITE SOURCE OF FREE<br>BOOTSTRAP THEMES</p>
                    <hr class="mb-4" style="width: 5%; margin: auto; height: 5px; border: none; color: #ff0000; background-color:#ff0000; opacity: 1;">
                    <p id="header-texts-2">Start Bootstrap can help you build better websites using the Bootstrap<br>framework! Just download a theme and start customizing, no strings attached!</p>
                    <button class="btn mt-4" id="header-btn">FIND OUT MORE</button>
                </div>
            </div>
        </div>
    </header>
    <!-- ========================= Section 02 ========================= -->
    <div class="sec-2 text-light text-center py-5" style="background-color: #f4623a;">
        <p class="display-6">We've got what you need!</p>
        <hr class="mb-4" style="width: 5%; margin: auto; height: 3px; border: none; color: #fff; background-color:#fff;
        opacity: 1;">
        <p class="w-md-50 m-auto">Start Bootstrap has everything you need to get your new website up and running in no time! Choose one of our open source, free to download, and easy to use themes! No strings attached!</p>
        <button class="btn mt-4 bg-light text-dark fw-bold" id="header-btn">GET STRATED!</button>
    </div>
    <!-- ========================= Section 03 ========================= -->
    <div class="sec-3 py-5 my-5">
        <div class="container text-center">
            <h2>At your Service</h2>
            <hr class="my-4" style="width: 5%; margin: auto; height: 3px; border: none; color: #f24516; background-color:#f24516;
            opacity: 1;">
            <div class="row text-center mt-5">
                <div class="col-md">
                    <img src="./images/diamond.png" alt="">
                    <p class="fw-bold mt-3 mb-0" style="font-size: 22px;">Sturdy Themes</p>
                    <p>Our themes are updated regularly to keep them bug free!</p>
                </div>
                <div class="col-md">
                    <img src="./images/uptodate.png" alt="">
                    <p class="fw-bold mt-3 mb-0" style="font-size: 22px;">Up to Date</p>
                    <p>All dependencies are kept current to keep things fresh.</p>
                </div>
                <div class="col-md">
                    <img src="./images/globe.png" alt="">
                    <p class="fw-bold mt-3 mb-0" style="font-size: 22px;">Ready to Publish</p>
                    <p>You can use this design as is, or you can make changes!</p>
                </div>
                <div class="col-md">
                    <img src="./images/heart.png" alt="">
                    <p class="fw-bold mt-3 mb-0" style="font-size: 22px;">Made with Love</p>
                    <p>Is it really open source if it's not made with love?</p>
                </div>
            </div>
        </div>
    </div>
    <!-- ========================= Section 04 ========================= -->
    <div class="container-fluid">
        <div class="row">
            <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/1.jpg" alt=""></div>
            <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/2.jpg" alt=""></div>
            <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/3.jpg" alt=""></div>
        </div>
        <div class="row">
            <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/4.jpg" alt=""></div>
            <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/5.jpg" alt=""></div>
            <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/6.jpg" alt=""></div>
        </div>
        <div class="row py-5" style="background-color: #343a40;">
            <div class="col text-center py-5">
                <h2 class="text-light">Free Download at Start Bootstrap!</h2>
                <button class="btn mt-4 bg-light text-dark fw-bold" id="header-btn">DOWNLOAD NOW!</button>
            </div>
        </div>
    </div>
    <!-- ========================= Section 05 ========================= -->
    <div class="container text-center py-5 my-5">
        <h2>Let's Get In Touch!</h2>
        <hr class="my-4" style="width: 5%; margin: auto; height: 3px; border: none; color: #f24516; background-color:#f24516;
        opacity: 1;">
        <p class="w-50 m-auto">Ready to start your next project with us? Give us a call or send us an email and we will get back to you as soon as possible!</p>
        <div class="row w-50 m-auto mt-5">
            <div class="col-md">
                <img src="./images/phone.png" alt="">
                <p>+1 (555) 123-4567</p>
            </div>
            <div class="col-md">
                <img src="./images/email.png" alt="">
                <a href="#" style="color: #f24516 !important; text-decoration: none;">contact@yourwebsite.com</a>
            </div>
        </div>
    </div>
    <!-- ========================= footer ========================= -->
    <div class="container-fluid text-center py-5" style="background-color: #f8f9fa;">
        <p class="mb-0">Copyright &copy; 2021 - Dabananda Mitra</p>
    </div>
    <!-- ========================= JavaScript ========================= -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
        $(document).ready(function() {
            $(body).scroll(function() {
                if ($(body).scroll() > 20) {
                    $("#navigation").addClass("nav-color");   
                }
                else {
                    $("#navigation").removeClass("nav-color");
                }
            });
        });
    </script>
</body>
</html>

标签: javascripthtmljquerycsstwitter-bootstrap

解决方案


您可以通过scrollTop以下方式使用(并检测滚动window,而不是body):

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(this).scrollTop() > 20) {
      $("#navigation").addClass("nav-color");
    } else {
      $("#navigation").removeClass("nav-color");
    }
  });
});

应用于您的代码段:

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(this).scrollTop() > 20) {
      $("#navigation").addClass("nav-color");
    } else {
      $("#navigation").removeClass("nav-color");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" href="./images/favicon.ico">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css" integrity="sha384-SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk" crossorigin="anonymous">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: sans-serif;
      text-decoration: none;
      list-style: none;
    }
    
    header {
      background: linear-gradient(rgba(45, 44, 48, 0.753), rgba(45, 44, 48, 0.753)), url(./images/bg-masthead.jpg);
      height: 100vh;
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
      color: white;
      font-weight: bold;
    }
    
    .navbar-brand {
      font-size: 20px;
    }
    
    .navbar {
      position: fixed;
      width: 100%;
      top: 0;
      left: 0;
    }
    
    #header-texts {
      height: 90vh;
      align-items: center;
      margin-top: 60px;
      height: 90vh;
    }
    
    #header-texts-1 {
      font-size: 55px;
    }
    
    #header-texts-2 {
      font-size: 20px;
      font-weight: normal;
    }
    
    #header-btn {
      background: #f24516;
      color: white;
      padding: 15px 20px;
      border-radius: 30px;
      letter-spacing: 0.8px;
    }
    
    #s-5:hover {
      border-bottom: 1px solid #f24516;
    }
    
    .nav-color {
      background-color: #ffffff;
      color: black;
    }
    /* ========================= Responsive ========================= */
    
    @media (max-width: 540px) {
      #header-texts-1 {
        font-size: 30px;
      }
      #header-texts-2 {
        font-size: 16px;
      }
    }
    
    @media (min-width: 992px) {
      .container {
        width: 100vw !important;
      }
      .navbar-expand-lg {
        background: transparent !important;
      }
      a {
        color: white !important;
      }
    }
  </style>
  <title>Creative</title>
</head>

<body>
  <header>
    <div class="container">
      <div class="row">
        <div class="col">
          <nav class="navbar navbar-expand-lg navbar-light bg-light" id="navigation">
            <div class="container-fluid">
              <a class="navbar-brand ms-lg-5" href="#">Start Bootstrap</a>
              <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                            <span class="navbar-toggler-icon"></span>
                            </button>
              <div class="collapse navbar-collapse justify-content-end" id="navbarNavAltMarkup">
                <div class="navbar-nav me-lg-5" id="nav-items">
                  <a class="nav-link active" aria-current="page" href="#">Home</a>
                  <a class="nav-link" href="#">About</a>
                  <a class="nav-link" href="#">Services</a>
                  <a class="nav-link" href="#">Protfolio</a>
                  <a class="nav-link" href="#">Contact</a>
                </div>
              </div>
            </div>
          </nav>
        </div>
      </div>
      <div class="row text-center" id="header-texts">
        <div class="col">
          <p id="header-texts-1">YOUR FAVORITE SOURCE OF FREE<br>BOOTSTRAP THEMES</p>
          <hr class="mb-4" style="width: 5%; margin: auto; height: 5px; border: none; color: #ff0000; background-color:#ff0000; opacity: 1;">
          <p id="header-texts-2">Start Bootstrap can help you build better websites using the Bootstrap<br>framework! Just download a theme and start customizing, no strings attached!</p>
          <button class="btn mt-4" id="header-btn">FIND OUT MORE</button>
        </div>
      </div>
    </div>
  </header>
  <!-- ========================= Section 02 ========================= -->
  <div class="sec-2 text-light text-center py-5" style="background-color: #f4623a;">
    <p class="display-6">We've got what you need!</p>
    <hr class="mb-4" style="width: 5%; margin: auto; height: 3px; border: none; color: #fff; background-color:#fff;
        opacity: 1;">
    <p class="w-md-50 m-auto">Start Bootstrap has everything you need to get your new website up and running in no time! Choose one of our open source, free to download, and easy to use themes! No strings attached!</p>
    <button class="btn mt-4 bg-light text-dark fw-bold" id="header-btn">GET STRATED!</button>
  </div>
  <!-- ========================= Section 03 ========================= -->
  <div class="sec-3 py-5 my-5">
    <div class="container text-center">
      <h2>At your Service</h2>
      <hr class="my-4" style="width: 5%; margin: auto; height: 3px; border: none; color: #f24516; background-color:#f24516;
            opacity: 1;">
      <div class="row text-center mt-5">
        <div class="col-md">
          <img src="./images/diamond.png" alt="">
          <p class="fw-bold mt-3 mb-0" style="font-size: 22px;">Sturdy Themes</p>
          <p>Our themes are updated regularly to keep them bug free!</p>
        </div>
        <div class="col-md">
          <img src="./images/uptodate.png" alt="">
          <p class="fw-bold mt-3 mb-0" style="font-size: 22px;">Up to Date</p>
          <p>All dependencies are kept current to keep things fresh.</p>
        </div>
        <div class="col-md">
          <img src="./images/globe.png" alt="">
          <p class="fw-bold mt-3 mb-0" style="font-size: 22px;">Ready to Publish</p>
          <p>You can use this design as is, or you can make changes!</p>
        </div>
        <div class="col-md">
          <img src="./images/heart.png" alt="">
          <p class="fw-bold mt-3 mb-0" style="font-size: 22px;">Made with Love</p>
          <p>Is it really open source if it's not made with love?</p>
        </div>
      </div>
    </div>
  </div>
  <!-- ========================= Section 04 ========================= -->
  <div class="container-fluid">
    <div class="row">
      <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/1.jpg" alt=""></div>
      <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/2.jpg" alt=""></div>
      <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/3.jpg" alt=""></div>
    </div>
    <div class="row">
      <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/4.jpg" alt=""></div>
      <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/5.jpg" alt=""></div>
      <div class="col-md px-0"><img class="w-100" src="./images/portfolio/thumbnails/6.jpg" alt=""></div>
    </div>
    <div class="row py-5" style="background-color: #343a40;">
      <div class="col text-center py-5">
        <h2 class="text-light">Free Download at Start Bootstrap!</h2>
        <button class="btn mt-4 bg-light text-dark fw-bold" id="header-btn">DOWNLOAD NOW!</button>
      </div>
    </div>
  </div>
  <!-- ========================= Section 05 ========================= -->
  <div class="container text-center py-5 my-5">
    <h2>Let's Get In Touch!</h2>
    <hr class="my-4" style="width: 5%; margin: auto; height: 3px; border: none; color: #f24516; background-color:#f24516;
        opacity: 1;">
    <p class="w-50 m-auto">Ready to start your next project with us? Give us a call or send us an email and we will get back to you as soon as possible!</p>
    <div class="row w-50 m-auto mt-5">
      <div class="col-md">
        <img src="./images/phone.png" alt="">
        <p>+1 (555) 123-4567</p>
      </div>
      <div class="col-md">
        <img src="./images/email.png" alt="">
        <a href="#" style="color: #f24516 !important; text-decoration: none;">contact@yourwebsite.com</a>
      </div>
    </div>
  </div>
  <!-- ========================= footer ========================= -->
  <div class="container-fluid text-center py-5" style="background-color: #f8f9fa;">
    <p class="mb-0">Copyright &copy; 2021 - Dabananda Mitra</p>
  </div>
  <!-- ========================= JavaScript ========================= -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
</body>

</html>


推荐阅读