见代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>侧边栏拖拽改变宽度,主区域自适应</title>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
}
body {
width: 100%;
height: 100vh;
display: flex;
}
aside {
height: 100%;
flex-shrink: 0;
position: relative;
display: flex;
}
#menu{
min-width: 200px;
max-width: 500px;
background-color: #333;
color: #fff;
font-weight: bold;
padding: 15px;
box-sizing: border-box;
}
.bar {
width: 5px;
height: 100%;
background-color: #333;
transition: 0.3s;
}
.bar:hover {
cursor: ew-resize;
background-color: #777;
}
main {
flex: 1;
background-color: #eee;
margin: 15px;
padding: 15px;
box-sizing: border-box;
}
</style>
</head>
<body>
<aside>
<ul id="menu">
<li>菜单一</li>
<li>菜单二</li>
<li>菜单三</li>
<li>菜单四</li>
<li>菜单五</li>
</ul>
<div class="bar" id="bar"></div>
</aside>
<main>
主区域
</main>
<script>
const menu = document.querySelector('#menu');
const bar = document.querySelector('#bar');
// 拖拽改变侧边栏宽度
bar.addEventListener('mousedown', (e) => {
let startX = e.clientX;
let startWidth = menu.offsetWidth;
// 鼠标移动事件
document.onmousemove = (e) => {
let moveX = e.clientX - startX;
let width = startWidth + moveX;
// 边界值
if (width < 200) {
width = 200;
}
if (width> 500) {
width = 500;
}
menu.style.width = width + 'px';
}
})
// 鼠标抬起事件
document.onmouseup = function () {
document.onmousemove = null;
}
</script>
</body>
</html>