用js制作导航栏下标随页面的变化而变化
时间: 2024-02-25 15:53:50 浏览: 18
可以使用JavaScript监听页面滚动事件,根据当前滚动位置动态修改导航栏下标的位置。
以下是一个简单的实现示例:
HTML结构:
```html
<nav>
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
<li><a href="#section4">Section 4</a></li>
</ul>
<div class="underline"></div> <!-- 下标元素 -->
</nav>
<div id="section1">Section 1</div>
<div id="section2">Section 2</div>
<div id="section3">Section 3</div>
<div id="section4">Section 4</div>
```
CSS样式:
```css
nav {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #eee;
}
nav ul {
display: flex;
justify-content: space-around;
list-style: none;
margin: 0;
padding: 0;
}
nav ul li {
margin: 0 10px;
}
nav ul li a {
text-decoration: none;
color: #333;
}
nav .underline {
position: absolute;
bottom: 0;
height: 2px;
background-color: #333;
transition: all 0.3s ease-in-out;
}
```
JavaScript代码:
```javascript
var nav = document.querySelector('nav');
var navHeight = nav.offsetHeight; // 获取导航栏高度
var underline = document.querySelector('.underline');
var sections = document.querySelectorAll('section');
// 监听页面滚动事件
window.addEventListener('scroll', function() {
var top = window.pageYOffset; // 获取当前滚动位置
// 遍历每个section元素,查找当前可见的元素
for (var i = 0; i < sections.length; i++) {
var section = sections[i];
var sectionTop = section.offsetTop - navHeight; // 获取section顶部位置
var sectionBottom = sectionTop + section.offsetHeight; // 获取section底部位置
// 判断当前位置是否在该section内
if (top >= sectionTop && top < sectionBottom) {
var left = section.offsetLeft; // 获取该section在导航栏中的位置
var width = section.offsetWidth; // 获取该section的宽度
underline.style.left = left + 'px'; // 设置下标的位置
underline.style.width = width + 'px'; // 设置下标的宽度
break;
}
}
});
```
以上代码中,先获取导航栏高度和下标元素,然后监听页面滚动事件,在滚动时遍历每个section元素,查找当前可见的元素,并根据该元素在导航栏中的位置和宽度动态修改下标的位置和宽度。