2.编写代码实现完整的响应式基础导航栏,如图所示分别是导航栏收起、在不同宽度屏幕中的展开状态。
时间: 2023-12-06 12:43:03 浏览: 69
由于您没有提供图示,我无法准确地模拟出导航栏的样式。但是,我可以提供一些编写响应式导航栏的代码,供您参考。
HTML 代码:
```
<nav>
<div class="logo">
<a href="#">Logo</a>
</div>
<ul class="nav-links">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
</ul>
<div class="burger">
<div class="line1"></div>
<div class="line2"></div>
<div class="line3"></div>
</div>
</nav>
```
CSS 代码:
```
nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
background-color: #333;
color: #fff;
}
.nav-links {
display: flex;
justify-content: space-around;
width: 50%;
}
.nav-links li {
list-style: none;
}
.nav-links a {
color: #fff;
text-decoration: none;
font-weight: bold;
}
.burger {
display: none;
cursor: pointer;
}
.burger div {
width: 25px;
height: 3px;
background-color: #fff;
margin: 5px;
}
@media screen and (max-width: 1024px) {
.nav-links {
width: 60%;
}
}
@media screen and (max-width: 768px) {
body {
overflow-x: hidden;
}
.nav-links {
position: absolute;
right: 0px;
height: 92vh;
top: 8vh;
background-color: #333;
display: flex;
flex-direction: column;
align-items: center;
width: 50%;
transform: translateX(100%);
transition: transform 0.5s ease-in;
}
.nav-links li {
opacity: 0;
}
.burger {
display: block;
}
}
.nav-active {
transform: translateX(0%);
}
@keyframes navLinkFade {
from {
opacity: 0;
transform: translateX(50px);
}
to {
opacity: 1;
transform: translateX(0px);
}
}
.toggle .line1 {
transform: rotate(-45deg) translate(-5px, 6px);
}
.toggle .line2 {
opacity: 0;
}
.toggle .line3 {
transform: rotate(45deg) translate(-5px, -6px);
}
```
JavaScript 代码:
```
const burger = document.querySelector('.burger');
const navLinks = document.querySelector('.nav-links');
const links = document.querySelectorAll('.nav-links li');
burger.addEventListener('click', () => {
navLinks.classList.toggle('nav-active');
links.forEach((link, index) => {
if (link.style.animation) {
link.style.animation = '';
} else {
link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.5}s`;
}
});
burger.classList.toggle('toggle');
});
```
这个代码会在不同屏幕宽度下创建响应式导航栏,并且在点击汉堡菜单按钮时,导航栏会展开或收起。您可以根据您的需求进行修改和调整。
阅读全文