需求
布局是 menu + left main + right main
其中 menu 和 left main 都需要可伸缩
三件套html css js实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Collapsible Layout</title>
<style>
/* General Reset */
body, html {
margin: 0;
padding: 0;
height: 100%;
}
/* Layout container */
.layout {
display: flex;
width: 100%;
height: 100%;
}
/* Menu Section */
.menu {
background-color: #333;
color: #fff;
width: 200px;
min-width: 50px;
transition: width 0.3s ease;
overflow: hidden;
display: flex;
align-items: center;
flex-direction: column;
}
.menu .toggle-btn {
background-color: #444;
color: #fff;
border: none;
padding: 10px;
margin: 10px;
cursor: pointer;
}
/* Left Main Section */
.left-main {
background-color: #f4f4f4;
color: #333;
width: 300px;
min-width: 100px;
transition: width 0.3s ease;
overflow: hidden;
display: flex;
align-items: center;
flex-direction: column;
}
.left-main .toggle-btn {
background-color: #ddd;
color: #333;
border: none;
padding: 10px;
margin: 10px;
cursor: pointer;
}
/* Right Main Section */
.right-main {
background-color: #000;
color: #fff;
flex: 1;
padding: 20px;
}
</style>
</head>
<body>
<div class="layout">
<div class="menu" id="menu">
<button class="toggle-btn" id="menuToggle">Menu</button>
</div>
<div class="left-main" id="leftMain">
<button class="toggle-btn" id="leftMainToggle">Left Main</button>
</div>
<div class="right-main">
<h1>Main Content</h1>
<p>This is the main content area.</p>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", () => {
const menu = document.getElementById("menu");
const leftMain = document.getElementById("leftMain");
const menuToggle = document.getElementById("menuToggle");
const leftMainToggle = document.getElementById("leftMainToggle");
// Load saved state
const menuState = localStorage.getItem("menuState");
const leftMainState = localStorage.getItem("leftMainState");
if (menuState) menu.style.width = menuState;
if (leftMainState) leftMain.style.width = leftMainState;
// Toggle menu collapse/expand
menuToggle.addEventListener("click", () => {
const newWidth = menu.style.width === "50px" ? "200px" : "50px";
menu.style.width = newWidth;
localStorage.setItem("menuState", newWidth);
});
// Toggle left-main collapse/expand
leftMainToggle.addEventListener("click", () => {
const newWidth = leftMain.style.width === "100px" ? "300px" : "100px";
leftMain.style.width = newWidth;
localStorage.setItem("leftMainState", newWidth);
});
});
</script>
</body>
</html>
react框架
可以通过 useState 和 useEffect 实现动态布局切换和持久化功能。
小注意点
在我所有组件都设置为 heigh: 100vh 之后,右侧还出现了滚动条。
解决方案:
确保在 index.css 中对 html 和 body 设置以下样式:
html, body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden; /* 防止内容溢出 */
}