新闻中心
实现滚动时显示/隐藏导航栏并激活导航链接的教程

本文档旨在提供一个实现以下功能的教程:导航栏在页面滚动时自动显示和隐藏,并且导航链接根据当前视口位置以及点击事件动态激活。我们将使用 HTML、CSS 和 J*aScript(包含 jQuery)来实现这些效果。通过本文,你将学习如何监听滚动事件、动态修改 CSS 样式以及处理导航链接的激活状态。
导航栏滚动显示/隐藏
实现导航栏在滚动时显示和隐藏的关键在于监听 window.onscroll 事件,并根据当前滚动位置与之前滚动位置的比较来动态修改导航栏的 top 样式属性。
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("n*barSection").style.top = "0";
} else {
document.getElementById("n*barSection").style.top = "-70px";
}
prevScrollpos = currentScrollPos;
};这段代码首先获取页面初始的滚动位置 prevScrollpos。然后在 window.onscroll 函数中,获取当前的滚动位置 currentScrollPos,并将其与 prevScrollpos 进行比较。如果 prevScrollpos 大于 currentScrollPos,说明用户向上滚动,此时将导航栏的 top 属性设置为 "0",使其显示。反之,如果用户向下滚动,则将 top 属性设置为 "-70px",使其隐藏。最后,更新 prevScrollpos 为 currentScrollPos,以便下一次滚动时进行比较。
注意事项:
青泥AI
青泥学术AI写作辅助平台
360
查看详情
- 确保你的导航栏元素具有 id="n*barSection" 属性,以便 J*aScript 代码能够找到它。
- 根据你的导航栏高度调整 -70px 的值。
- 为了使过渡效果更平滑,可以在 CSS 中为导航栏添加 transition 属性。
激活导航链接
激活导航链接需要两个功能:一是点击导航链接时,平滑滚动到对应的 section,并激活该链接;二是页面滚动时,根据当前视口位置,自动激活对应的导航链接。
点击激活
以下代码使用 jQuery 实现点击导航链接时的平滑滚动和激活效果:
$(document).ready(function() {
$(document).on("scroll", onScroll);
//smoothscroll
$(".n*bar-toggler").on("click", function(e) {
e.preventDefault();
$(document).off("scroll");
$(".closeIcon").on("click", function(e) {
$(this).removeClass("active");
});
$(this).addClass("active");
var target = $(this).parents("div.container-fluid").find(".n*bar-brand").attr("href")
menu = target;
$target = $(target);
$("html, body")
.stop()
.animate({
scrollTop: $target.offset().top + 2,
},
500,
"swing",
function() {
window.location.hash = target;
$(document).on("scroll", onScroll);
}
);
});
});这段代码首先在文档加载完成后,绑定 scroll 事件到 onScroll 函数。然后,监听导航链接的 click 事件。当点击链接时,首先阻止默认行为,然后移除所有导航链接的 active 类,并为当前点击的链接添加 active 类。接着,使用 animate 函数实现平滑滚动到目标 section 的效果。在滚动完成后,更新 URL 的 hash 值,并重新绑定 scroll 事件。
注意事项:
- 确保引入 jQuery 库。
- e.preventDefault() 用于阻止默认的链接跳转行为。
- $(document).off("scroll") 和 $(document).on("scroll", onScroll) 用于在滚动过程中暂停和恢复滚动事件的监听,避免冲突。
- 500 是动画的持续时间,可以根据需要调整。
- swing 是动画的缓动函数,也可以选择其他缓动函数。
滚动激活
以下代码实现页面滚动时,根据当前视口位置自动激活对应的导航链接:
function onScroll(event) {
var scrollPos = $(document).scrollTop();
$("#n*barSection a").each(function() {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (
refElement.position().top <= scrollPos &&
refElement.position().top + refElement.height() > scrollPos
) {
$("#n*barSection ul li a").removeClass("active");
currLink.addClass("active");
} else {
currLink.removeClass("active");
}
});
}这段代码首先获取当前的滚动位置 scrollPos。然后,遍历所有的导航链接。对于每个链接,获取其 href 属性对应的 section 元素。如果该 section 元素在视口范围内,则移除所有导航链接的 active 类,并为当前链接添加 active 类。否则,移除当前链接的 active 类。
注意事项:
- 确保每个导航链接的 href 属性与对应的 section 元素的 id 属性一致。
- refElement.position().top 获取 section 元素相对于文档顶部的距离。
- refElement.height() 获取 section 元素的高度。
完整示例代码
以下是完整的 HTML、CSS 和 J*aScript 示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>N*bar Scroll & Active</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container" id="n*barSection">
<n* class="n*bar n*bar-expand-lg" aria-label="Offcanvas n*bar large">
<div class="container-fluid">
<a class="n*bar-brand" href="#heroSection">@@##@@</a>
<button class="n*bar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasN*bar2" aria-controls="offcanvasN*bar2" aria-label="Toggle n*igation">
<span class="n*bar-toggler-icon"></span>
</button>
<div class="offcanvas offcanvas-end mx-auto" tabindex="-1" id="offcanvasN*bar2" aria-labelledby="offcanvasN*bar2Label">
<div class="offcanvas-header">
<a class="n*bar-brand" href="#heroSection">@@##@@</a>
<button type="button" data-bs-dismiss="offcanvas" aria-label="Close" class="closeButton">
@@##@@
</button>
<!-- <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close"></button> -->
</div>
<div class="offcanvas-body">
<ul class="n*bar-n* align-items-center mx-auto mb-2 mb-lg-0">
<li class="n*-item heroSection">
<a class="n*-link active" href="#heroSection">About Us</a>
</li>
<li class="n*-item serviceSection">
<a class="n*-link" href="#serviceSection">Services</a>
</li>
<li class="n*-item workSection">
<a class="n*-link" href="#workSection">Work</a>
</li>
</ul>
<div class="contact-us-button">
<button class="btn blue-button">
<a href="#contactSection" style="text-decoration: none; color: white">Contact Us</a>
</button>
</div>
</div>
</div>
</div>
</n*>
</div>
<section id="heroSection">
Hero Section
</section>
<section id="workSection">
Work Section
</section>
<section id="aboutusSection">
About Us Section
</section>
<section id="serviceSection">
Service Section
</section>
<section id="contactSection">
Contact Section
</section>
<script src="script.js"></script>
</body>
</html>* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
font-family: 'Poppins', sans-serif !important;
}
#n*barSection {
position: sticky !important;
top: 0; /* 添加此行 */
background: white !important;
transition: all .25s ease-in-out 0s !important;
z-index: 1000; /* 确保导航栏在其他内容之上 */
}
Section {
margin-bottom: 150px;
height: 100vh;
display: flex;
align-items: center;
justify-content: center; /* 水平居中内容 */
font-size: 2em; /* 增大字体,更易于查看滚动效果 */
}
.blue-button {
padding: 12px 24px !important;
background-color: #3130F2 !important;
border-radius: 37px !important;
color: white !important;
font-weight: 700 !important;
}
.blue-button:hover {
background-color: #FECD00 !important;
/* color: #3130F2 !important; */
transition: all .25s ease-in-out 0s !important;
}
.closeButton {
background-color: rgba(254, 205, 0, 0.4);
/* border: none; */
border: 1px solid transparent;
border-radius: 10px;
}
.closeButton:hover {
background-color: rgba(254, 205, 0, 0.8);
/* background-color: rgba(49, 48, 242, 0.5) ; */
/* border: none; */
border: 1px solid #3130f2;
border-radius: 10px;
}
.offcanvas-backdrop.show
{
opacity: 0.8;
}
.offcanvas-backdrop {
background-color: #8E90A6;
}
.closeIcon {
width: 40px;
height: 40px;
}
.n*-link {
padding: 0px !important;
font-weight: 400;
font-size: 20px !important;
line-height: 40px !important;
letter-spacing: 0.08em !important;
}
.n*-link:hover {
color: #3130F2 !important;
border-bottom-left-radius: 0%;
border-bottom-right-radius: 0%;
border-bottom: 3px solid #FECD00 !important;
cursor: pointer !important;
transition: all .18s ease-in-out 0s !important;
}
.n*-item:active a {
background-color: #8E90A6 !important;
}
.n*bar-n* .n*-link.active,
.n*bar-n* .show>.n*-link {
color: #3130F2 !important;
font-weight: 600;
border-radius: 37px;
border-bottom-left-radius: 0%;
border-bottom-right-radius: 0%;
border-bottom: 3px solid #FECD00;
}
.btn:hover {
border-color: transparent !important;
}var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("n*barSection").style.top = "0";
} else {
document.getElementById("n*barSection").style.top = "-70px";
}
prevScrollpos = currentScrollPos;
};
$(document).ready(function() {
$(document).on("scroll", onScroll);
//smoothscroll
$(".n*bar-toggler").on("click", function(e) {
e.preventDefault();
$(document).off("scroll");
$(".closeIcon").on("click", function(e) {
$(this).removeClass("active");
});
$(this).addClass("active");
var target = $(this).parents("div.container-fluid").find(".n*bar-brand").attr("href")
menu = target;
$target = $(target);
$("html, body")
.stop()
.animate({
scrollTop: $target.offset().top + 2,
},
500,
"swing",
function() {
window.location.hash = target;
$(document).on("scroll", onScroll);
}
);
});
});
function onScroll(event) {
var scrollPos = $(document).scrollTop();
$("#n*barSection a").each(function() {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (
refElement.position().top <= scrollPos &&
refElement.position().top + refElement.height() > scrollPos
) {
$("#n*barSection ul li a").removeClass("active");
currLink.addClass("active");
} else {
currLink.removeClass("active");
}
});
}总结:
通过以上步骤,你可以实现导航栏在滚动时自动显示和隐藏,并且导航链接根据当前视口位置以及点击事件动态激活。这个教程提供了一个基础的实现,你可以根据自己的需求进行修改和扩展。例如,你可以添加更多的导航链接和 section,或者修改动画效果和样式。记住,理解代码背后的逻辑是关键,这样才能更好地应用和定制这些技术。

以上就是实现滚动时显示/隐藏导航栏并激活导航链接的教程的详细内容,更多请关注其它相关文章!
# 单选框
# smo包括seo和什么
# 合肥seo网络推广策略
# 德惠百度关键词快速排名
# 江西seo什么价格
# 峡山公司网站优化招聘网
# 招商平台型网站建设
# 网站优化报价流程图片
# 重庆seo新站优化价格
# 健康关注营销推广方案
# 迁西专业的seo优化
# 绑定
# 并为
# 设置为
# 文档
# 使其
# css
# 移除
# 这段
# 你可以
# 表单
# ai
# svg
# go
# ajax
# bootstrap
# js
# html
# jquery
# java
# javascript
相关栏目:
【
科技资讯46185 】
【
网络学院92790 】
相关推荐:
小红书怎么解除第三方平台绑定_小红书多平台登录解绑方法介绍
HTML空白字符处理机制:渲染、DOM与编码实践
如何在复杂的电商平台中优雅地管理共享资源并确保正确重定向,使用spryker-shop/resource-share-page模块助你一臂之力
韩剧圈正版入口页面_韩剧圈官网登录链接
steam官方入口大全 steam账号注册及操作指南
在J*aScript中复现SciPy的B样条拟合与求值:关键考量
Lar*el表单中优雅地处理“返回”按钮以规避验证:最佳实践指南
解决Django多数据库/多Schema环境下外键迁移问题
如何将HTML表格多行数据保存到Google Sheet
使用 Pandas 高效处理 .dat 文件:字符清理与数据计算
深入理解J*a链表中的IPosition接口与使用
怎样更改Windows系统的默认安装路径_避免C盘爆满的终极设置【技巧】
Composer如何在生产环境安全地执行composer update
QQ邮箱在线登录平台 QQ邮箱个人邮箱网页版入口
生成rdflib自定义SPARQL函数:参数匹配与实践指南
steam官方网页快速访问 steam账号注册全流程
J*aScript数组对象转换:按指定键分组与值收集
将HTML Canvas内容转换为可上传的图像文件(File对象)
PHP中获取MongoDB服务器运行时间(Uptime)的专业指南
火锅吃太多会怎样 火锅吃太多会上火吗
qq音乐在线播放入口_qq音乐电脑版登录链接
2026年发布! 美少女养成动作RPG《神剑少女战记》发布实机演示
React中useState与局部变量:理解组件状态管理与渲染机制
百度网盘网页版入口 百度网盘网页版官方登录网址
使用Pandas转换并合并DataFrame:多列映射至统一结构
Go语言中对Map值调用带指针接收者方法:原理与最佳实践
如何使用 Excel 发布器与 Power BI 分享 Excel 洞察
sublime如何配置Python开发环境_将sublime打造成轻量级Python IDE
Mac终端命令大全_Mac常用Terminal指令速查
深入理解J*a编译器的兼容性选项:从-source到--release
谷歌google账号注册详细步骤 谷歌账号注册官方教程
QQ网页版官方账号入口 QQ网页版网页版登录指南
sublime如何只显示或隐藏特定类型文件_sublime侧边栏文件过滤
俄罗斯方块最新版入口 俄罗斯方块在线玩官网入口
解决Rails应用中内容错位与Turbo警告:meta标签误用导致富文本渲染异常
AO3官方可用镜像 Archive of Our Own网页版最新入口
俄罗斯搜索引擎Yandex指南 附2025年免登录官网入口
J*aScriptWebpack优化_J*aScript构建工具实战
C++如何解决segmentation fault_C++段错误调试与原因分析
聚水潭ERP登录页面入口 聚水潭ERP官网登录界面
蓝湖怎样用切图标注提对接效率_蓝湖用切图标注提对接效率【设计对接】
DLsite中文平台入口 DLsite官网内容在线查看
天眼查企业查询官网入口 天眼查官方网页版查询
蛙漫画网页版全站入口 蛙漫热门作品免费浏览
React Router v6 教程:构建认证保护的私有路由与重定向策略
UC浏览器官网入口2025最新 UC浏览器网页版正式地址
动漫花园资源网使用步骤_动漫花园资源网下载流程
AI抖音网页版免费视频入口 AI抖音网页端最新视频实时观看
微博网页版直接访问 微博网页版账号管理快速入口
Python Socket多播通信中指定源IP地址的实践指南


2025-10-08
浏览次数:次
返回列表
{
opacity: 0.8;
}
.offcanvas-backdrop {
background-color: #8E90A6;
}
.closeIcon {
width: 40px;
height: 40px;
}
.n*-link {
padding: 0px !important;
font-weight: 400;
font-size: 20px !important;
line-height: 40px !important;
letter-spacing: 0.08em !important;
}
.n*-link:hover {
color: #3130F2 !important;
border-bottom-left-radius: 0%;
border-bottom-right-radius: 0%;
border-bottom: 3px solid #FECD00 !important;
cursor: pointer !important;
transition: all .18s ease-in-out 0s !important;
}
.n*-item:active a {
background-color: #8E90A6 !important;
}
.n*bar-n* .n*-link.active,
.n*bar-n* .show>.n*-link {
color: #3130F2 !important;
font-weight: 600;
border-radius: 37px;
border-bottom-left-radius: 0%;
border-bottom-right-radius: 0%;
border-bottom: 3px solid #FECD00;
}
.btn:hover {
border-color: transparent !important;
}