帮我写一个侧边栏在右边可点击收起的布局
时间: 2024-02-26 07:57:47 浏览: 170
侧边栏布局
好的,这里提供一种实现方式,使用 HTML、CSS 和 JavaScript 实现:
HTML 结构:
```
<div class="sidebar">
<div class="toggle-btn">
<span></span>
<span></span>
<span></span>
</div>
<ul>
<li><a href="#">菜单项1</a></li>
<li><a href="#">菜单项2</a></li>
<li><a href="#">菜单项3</a></li>
</ul>
</div>
```
CSS 样式:
```
.sidebar {
position: fixed;
top: 0;
right: -250px;
width: 250px;
height: 100%;
background: #333;
z-index: 9999;
transition: all 0.3s ease-in-out;
}
.sidebar.show {
right: 0;
}
.toggle-btn {
position: absolute;
top: 20px;
right: -40px;
width: 40px;
height: 40px;
background: #444;
cursor: pointer;
z-index: 1;
}
.toggle-btn span {
display: block;
width: 20px;
height: 2px;
background: #fff;
margin: 8px auto;
transition: all 0.3s ease-in-out;
}
.toggle-btn.active span:nth-child(1) {
transform: rotate(45deg) translate(5px, 5px);
}
.toggle-btn.active span:nth-child(2) {
opacity: 0;
}
.toggle-btn.active span:nth-child(3) {
transform: rotate(-45deg) translate(5px, -5px);
}
ul {
list-style: none;
margin: 50px 0 0 0;
padding: 0;
}
li {
margin: 0;
}
a {
display: block;
padding: 10px;
color: #fff;
text-decoration: none;
transition: all 0.3s ease-in-out;
}
a:hover {
background: #555;
}
```
JavaScript 代码:
```
const sidebar = document.querySelector('.sidebar');
const toggleBtn = document.querySelector('.toggle-btn');
toggleBtn.addEventListener('click', () => {
sidebar.classList.toggle('show');
toggleBtn.classList.toggle('active');
});
```
这段代码实现的效果是,当点击 `toggleBtn` 时,`sidebar` 右侧向左滑动,同时 `toggleBtn` 变成一个关闭按钮,再次点击时回到初始状态。
阅读全文