<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>滚动固定导航栏示例</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
line-height: 1.6;
padding-top: 60px; /* 为固定导航栏预留空间 */
}
/* 导航栏样式 */
.navbar {
background-color: #333;
color: white;
padding: 15px 0;
width: 100%;
transition: all 0.3s ease;
}
.navbar.fixed {
position: fixed;
top: 0;
left: 0;
z-index: 1000;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.logo {
font-size: 24px;
font-weight: bold;
}
.nav-links {
display: flex;
list-style: none;
}
.nav-links li {
margin-left: 20px;
}
.nav-links a {
color: white;
text-decoration: none;
transition: color 0.3s;
}
.nav-links a:hover {
color: #4CAF50;
}
/* 内容区域样式 */
.content {
padding: 40px 0;
}
.section {
height: 600px;
padding: 40px;
margin-bottom: 20px;
background-color: #f4f4f4;
}
.footer {
text-align: center;
padding: 20px;
background-color: #333;
color: white;
}
.footer a {
color: #4CAF50;
text-decoration: none;
}
</style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar">
<div class="container">
<div class="logo">网站LOGO</div>
<ul class="nav-links">
<li><a href="#home">首页</a></li>
<li><a href="#about">关于</a></li>
<li><a href="#services">服务</a></li>
<li><a href="#contact">联系</a></li>
</ul>
</div>
</nav>
<!-- 内容区域 -->
<div class="content">
<section id="home" class="section">
<h1>首页区域</h1>
<p>向下滚动页面,导航栏会固定在顶部。</p>
</section>
<section id="about" class="section">
<h1>关于我们</h1>
<p>这里是关于我们的内容...</p>
</section>
<section id="services" class="section">
<h1>我们的服务</h1>
<p>这里是我们提供的服务内容...</p>
</section>
<section id="contact" class="section">
<h1>联系我们</h1>
<p>这里是联系方式...</p>
</section>
</div>
<!-- 页脚 -->
<footer class="footer">
</footer>
<!-- 引入jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- 滚动固定导航栏的jQuery代码 -->
<script>
$(document).ready(function() {
// 获取导航栏的初始位置
var navbar = $('.navbar');
var navbarOffsetTop = navbar.offset().top;
// 滚动事件处理
$(window).scroll(function() {
// 检查滚动位置
if ($(window).scrollTop() >= navbarOffsetTop) {
navbar.addClass('fixed');
} else {
navbar.removeClass('fixed');
}
});
// 平滑滚动到锚点
$('a[href^="#"]').on('click', function(event) {
event.preventDefault();
var target = $(this.getAttribute('href'));
if (target.length) {
$('html, body').stop().animate({
scrollTop: target.offset().top - navbar.outerHeight()
}, 800);
}
});
});
</script>
</body>
</html>
7791

被折叠的 条评论
为什么被折叠?



