<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
}
#sidebar {
position: fixed;
top: 0;
left: -250px; /* 控制初始隐藏侧边栏 */
width: 250px;
height: 100vh;
background: #f2f2f2;
transition: left 0.3s ease-in-out;
z-index: 9999;
}
#sidebar.active {
left: 0; /* 显示侧边栏 */
}
#content {
margin-left: 250px; /* 侧边栏宽度 */
padding: 20px;
}
#sidebar ul {
list-style-type: none;
padding: 0;
margin: 0;
}
#sidebar ul li {
position: relative;
padding: 10px 0;
}
#sidebar ul li a {
color: #333;
text-decoration: none;
padding: 10px 20px;
display: block;
}
#sidebar ul li a:hover {
background-color: #ddd;
}
#sidebar ul li ul {
position: absolute;
left: 100%;
top: 0;
width: 250px;
display: none; /* 初始隐藏二级菜单 */
}
#sidebar ul li:hover ul {
display: block; /* 鼠标悬停时显示二级菜单 */
}
#sidebar ul li ul li {
padding: 5px 0;
}
#sidebar ul li ul li a {
padding-left: 40px; /* 调整二级菜单的缩进 */
}
#overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
background-color: rgba(0, 0, 0, 0.5);
display: none; /* 初始隐藏遮罩层 */
z-index: 9998;
}
.toggle-btn {
display: inline-block;
padding: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="sidebar">
<ul>
<li><a href="#">菜单1</a></li>
<li>
<a href="#">菜单2</a>
<ul>
<li><a href="#">子菜单1</a></li>
<li><a href="#">子菜单2</a></li>
</ul>
</li>
<li><a href="#">菜单3</a></li>
</ul>
</div>
<div id="content">
<div class="toggle-btn" onclick="toggleSidebar()">打开/关闭侧边栏</div>
<h1>主要内容区域</h1>
</div>
<div id="overlay" onclick="toggleSidebar()"></div>
<script>
var sidebar = document.getElementById('sidebar');
var overlay = document.getElementById('overlay');
function toggleSidebar() {
sidebar.classList.toggle('active');
overlay.style.display = sidebar.classList.contains('active') ? 'block' : 'none';
}
</script>
</body>
</html>