
本教程详细介绍了如何使用纯javascript实现网页导航栏在用户滚动页面时动态改变背景色的效果。通过监听`window`的`scroll`事件,并根据滚动距离判断,动态地添加或移除css类,从而实现导航栏从透明到实色(或任意指定颜色)的平滑过渡,提升用户体验。
在现代网页设计中,导航栏(Navbar)通常被设计为固定在页面顶部,并可能在用户向下滚动页面时改变其外观,例如从透明变为带有背景色。这种效果可以增强页面的视觉层次感和用户体验。实现这一功能的核心原理是利用JavaScript监听浏览器的滚动事件,并根据当前的滚动位置动态地修改导航栏元素的CSS类。
具体来说,我们将采取以下步骤:
首先,确保你的导航栏HTML结构包含一个易于JavaScript访问的唯一标识符,例如一个id属性。在以下示例中,我们将为navigation-wrap这个div元素添加id="myNav"。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>滚动时导航栏背景变化</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <link rel="stylesheet" href="style.css"> <!-- 引入自定义CSS -->
</head>
<body>
  <div id="myNav" class="navigation-wrap start-header start-style">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <nav class="navbar navbar-expand-md navbar-light">
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-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 ml-auto py-4 py-md-0">
                <li class="nav-item pl-4 pl-md-0 ml-0 ml-md-4 active">
                  <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Home</a>
                  <div class="dropdown-menu">
                    <a class="dropdown-item" href="#">Action</a>
                    <a class="dropdown-item" href="#">Another action</a>
                  </div>
                </li>
                <li class="nav-item pl-4 pl-md-0 ml-0 ml-md-4">
                  <a class="nav-link" href="#">Blogs</a>
                </li>
                <li class="nav-item pl-4 pl-md-0 ml-0 ml-md-4">
                  <a class="nav-link" href="#">Contact</a>
                </li>
              </ul>
            </div>
          </nav>
        </div>
      </div>
    </div>
  </div>
  <!-- 确保页面有足够高度以触发滚动 -->
  <div style="min-height: 150vh; background-color: #f8f9fa; padding-top: 100px; text-align: center;">
    <h1>向下滚动查看导航栏变化</h1>
    <p>页面内容区域...</p>
  </div>
  <script src="script.js"></script> <!-- 引入自定义JavaScript -->
</body>
</html>为了实现背景色的切换,我们需要定义导航栏在不同状态下的样式。初始状态下,导航栏可以是透明的。当页面滚动到一定距离后,我们将为其添加一个CSS类,该类会设置背景色。
以下是style.css文件中的关键CSS代码片段:
@import url("https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i&subset=devanagari,latin-ext");
body {
  font-family: "Poppins", sans-serif;
  font-size: 16px;
  line-height: 24px;
  font-weight: 400;
  background-color: #fff;
  overflow-x: hidden;
  transition: all 200ms linear;
  min-height: 200vh; /* 确保页面可滚动 */
}
.navigation-wrap {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 1000;
  transition: all 0.3s ease-out; /* 添加过渡效果,使背景切换平滑 */
}
.start-header {
  opacity: 1;
  transform: translateY(0);
  padding: 20px 0;
  box-shadow: 0 10px 30px 0 rgba(138, 155, 165, 0.2);
  transition: all 0.3s ease-out;
  background-color: transparent; /* 初始状态透明 */
}
/* 当页面滚动后,导航栏应用的样式 */
.navigation-wrap.scrolled-bg { /* 自定义一个类来添加背景色 */
  background-color: #ffffff; /* 滚动后背景色变为白色 */
  box-shadow: 0 5px 10px 0 rgba(138, 155, 165, 0.15); /* 调整阴影 */
  padding: 10px 0; /* 调整内边距 */
}
/* 如果使用Bootstrap的背景工具类,例如 bg-dark */
.navigation-wrap.bg-dark {
  background-color: #343a40 !important; /* Bootstrap的深色背景 */
  box-shadow: 0 5px 10px 0 rgba(138, 155, 165, 0.15);
  padding: 10px 0;
}
/* 其他原始样式 */
.navbar-light .navbar-toggler-icon {
  width: 24px;
  height: 17px;
  background-image: none;
  position: relative;
  border-bottom: 1px solid #212121; /* 初始为深色 */
  transition: all 300ms linear;
}
.navbar-light .navbar-toggler-icon:after,
.navbar-light .navbar-toggler-icon:before {
  width: 24px;
  position: absolute;
  height: 1px;
  background-color: #212121; /* 初始为深色 */
  top: 0;
  left: 0;
  content: "";
  z-index: 2;
  transition: all 300ms linear;
}
.navigation-wrap.bg-dark .navbar-light .navbar-toggler-icon {
    border-bottom-color: #fff; /* 滚动后图标变为白色 */
}
.navigation-wrap.bg-dark .navbar-light .navbar-toggler-icon:after,
.navigation-wrap.bg-dark .navbar-light .navbar-toggler-icon:before {
    background-color: #fff; /* 滚动后图标变为白色 */
}
.nav-link {
  color: #212121 !important; /* 初始链接颜色 */
  font-weight: 500;
  transition: all 200ms linear;
}
.navigation-wrap.bg-dark .nav-link {
  color: #ffffff !important; /* 滚动后链接颜色变为白色 */
}
.nav-item:hover .nav-link {
  color: #0087ff !important;
}
/* ... 其他CSS样式保持不变 ... */说明:
现在,我们编写JavaScript代码来监听滚动事件并动态修改导航栏的类。
在script.js文件中添加以下代码:
// 当DOM内容加载完毕后执行
document.addEventListener('DOMContentLoaded', () => {
  // 获取导航栏元素
  const myNav = document.getElementById("myNav");
  // 定义滚动处理函数
  function navScroll() {
    // 检查页面垂直滚动距离是否超过50像素
    if (window.scrollY > 50) {
      // 如果滚动距离超过阈值,添加 bg-dark 类(或 scrolled-bg)
      // 注意:这里使用 bg-dark 是为了与原始解决方案保持一致,它假定Bootstrap的bg-dark类存在。
      // 如果不使用Bootstrap,或者需要自定义颜色,请使用如 'scrolled-bg' 这样的自定义类。
      myNav.className = "navigation-wrap bg-dark start-header start-style";
    } else {
      // 如果滚动距离在阈值之内(或回到顶部),恢复默认类
      myNav.className = "navigation-wrap start-header start-style";
    }
  }
  // 添加滚动事件监听器
  window.addEventListener('scroll', navScroll);
  // 页面加载时也执行一次,以防页面刷新时已处于滚动状态
  navScroll();
});代码解释:
// 使用 classList 替代 className
if (window.scrollY > 50) {
  myNav.classList.add('bg-dark'); // 添加深色背景类
  // myNav.classList.add('scrolled-bg'); // 如果使用自定义类
} else {
  myNav.classList.remove('bg-dark'); // 移除深色背景类
  // myNav.classList.remove('scrolled-bg'); // 如果使用自定义类
}这种方法更健壮,因为它不会干扰已有的其他类。在实际项目中,建议优先使用classList API。
性能优化(滚动节流/防抖): scroll事件触发非常频繁,频繁的DOM操作可能导致性能问题。在生产环境中,建议对scroll事件进行节流(throttle)或防抖(debounce)处理。
// 简单的节流实现示例
function throttle(func, delay) {
let timeoutId;
let lastArgs;
let lastThis;
let lastResult;
let lastCallTime = 0;return function(...args) { const now = Date.now(); lastArgs = args; lastThis = this;
if (now - lastCallTime < delay) {
  if (timeoutId) clearTimeout(timeoutId);
  timeoutId = setTimeout(() => {
    lastCallTime = now;
    lastResult = func.apply(lastThis, lastArgs);
    timeoutId = null;
  }, delay - (now - lastCallTime));
} else {
  lastCallTime = now;
  lastResult = func.apply(lastThis, lastArgs);
}
return lastResult;}; }
// 将 navScroll 函数包装在节流函数中 // window.addEventListener('scroll', throttle(navScroll, 100));
CSS 类命名与管理: 教程中使用了Bootstrap的bg-dark类。如果你不使用Bootstrap或需要更精细的控制,可以定义自己的CSS类
以上就是在网页滚动时动态改变导航栏背景色的实现指南的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号