实现思路
- 媒体查询:使用CSS媒体查询,当屏幕宽度小于600px时,设置导航栏为垂直排列。
- JavaScript操作:通过JavaScript获取按钮元素和导航栏元素,为按钮添加点击事件,在点击时切换导航栏的显示或隐藏状态。
关键代码示例
- HTML部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Responsive Navbar</title>
</head>
<body>
<button id="menuButton">菜单</button>
<nav id="navbar">
<a href="#">首页</a>
<a href="#">关于</a>
<a href="#">服务</a>
<a href="#">联系</a>
</nav>
<script src="script.js"></script>
</body>
</html>
- CSS部分(styles.css)
nav {
display: flex;
justify-content: space-around;
}
@media (max-width: 600px) {
nav {
flex-direction: column;
display: none;
}
}
- JavaScript部分(script.js)
const menuButton = document.getElementById('menuButton');
const navbar = document.getElementById('navbar');
menuButton.addEventListener('click', () => {
if (navbar.style.display === 'none' || navbar.style.display === '') {
navbar.style.display = 'flex';
} else {
navbar.style.display = 'none';
}
});