|
效果
完整代码
HTML+JS
- <nav class="nav-bar">
- <ul>
- <li class="active"><i class="fas fa-home"></i>首页</li>
- <li><i class="fas fa-info-circle"></i>关于</li>
- <li><i class="fas fa-cogs"></i>服务</li>
- <li><i class="fas fa-envelope"></i>联系</li>
- <div class="slider"></div>
- </ul>
- </nav>
- <div class="content">
- <!-- 页面内容 -->
- </div>
- <script >
- let lastScrollTop = 0;
- window.addEventListener('scroll', function() {
- let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
- if (scrollTop > lastScrollTop) {
- document.querySelector('.nav-bar').style.opacity = '0';
- } else {
- document.querySelector('.nav-bar').style.opacity = '1';
- }
- lastScrollTop = scrollTop;
- });
- // 添加导航项点击事件和滑动效果
- const slider = document.querySelector('.nav-bar .slider');
- const navItems = document.querySelectorAll('.nav-bar li');
- function moveSlider(item) {
- slider.style.width = `${item.offsetWidth}px`;
- slider.style.left = `${item.offsetLeft}px`;
- }
- navItems.forEach(item => {
- item.addEventListener('click', function() {
- document.querySelector('.nav-bar li.active').classList.remove('active');
- this.classList.add('active');
- moveSlider(this);
- });
- });
- // 初始化滑块位置
- moveSlider(document.querySelector('.nav-bar li.active'));
- </script>
复制代码 CSS
- <style>
- body {
- margin: 0;
- padding: 0;
- font-family: Arial, sans-serif;
- }
- .nav-bar {
- position: fixed;
- top: 20px;
- width: 100%;
- background-color: rgba(51, 51, 51, 0.8);
- transition: opacity 0.3s ease;
- }
- .nav-bar ul {
- list-style-type: none;
- padding: 0;
- margin: 0;
- display: flex;
- justify-content: space-around;
- position: relative;
- }
- .nav-bar li {
- padding: 15px;
- color: white;
- cursor: pointer;
- position: relative;
- transition: all 0.3s ease;
- z-index: 1;
- }
- .nav-bar li::after {
- content: '';
- position: absolute;
- bottom: 0;
- left: 0;
- width: 0;
- height: 2px;
- background-color: #fff;
- transition: width 0.3s ease;
- }
- .nav-bar li:hover::after,
- .nav-bar li.active::after {
- width: 100%;
- }
- .nav-bar li.active {
- background-color: rgba(255, 255, 255, 0.2);
- }
- .nav-bar .slider {
- position: absolute;
- bottom: 0;
- left: 0;
- height: 100%;
- background-color: rgba(255, 255, 255, 0.2);
- transition: all 0.3s ease;
- }
- .nav-bar li i {
- margin-right: 5px;
- }
- .content {
- height: 2000px; /* 用于模拟长页面 */
- }
- </style>
复制代码
|
|