最终效果
最近个人项目需要实现一个左右分栏且左右宽度可以手工拖动调节的web页面,这里记录下实现过程,效果如下图,整个web页面包含左右两个分栏,中间是个4px像素的拖动条,鼠标移动到上面可以左右拖动改变左右分栏的宽度。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>web分栏宽度可调节示例</title>
</head>
<body>
<div id="container">
<div id="left">left</div>
<div id="resize"></div>
<div id="right">right</div>
</div>
<script src="resize.js"></script>
</body>
</html>
CSS
body {
margin: 0;
overflow-y: hidden;
}
#container {
width: 100%;
height: 100vh;
display: flex;
flex-wrap: nowrap;
align-items: stretch;
}
#left {
width: calc(30% - 4px);
background-color:indianred;
}
#resize {
width: 4px;
height: 100vh;
cursor: ew-resize;
}
#resize:hover {
background-color: blue;
}
#right {
width: 70%;
/* height: 100vh; */
background-color:green;
}
javascript
window.onload = function() {
var resize = document.getElementById('resize');
var left = document.getElementById('left');
var right = document.getElementById('right');
var container = document.getElementById('container');
resize.onmousedown = function(e) {
// 记录鼠标按下时的x轴坐标
var preX = e.clientX;
resize.left = resize.offsetLeft;
document.onmousemove = function(e) {
var curX = e.clientX;
var deltaX = curX - preX;
var leftWidth = resize.left + deltaX;
// 左边区域的最小宽度限制为64px
if (leftWidth < 64) leftWidth = 64;
// 右边区域最小宽度限制为64px
if (leftWidth > container.clientWidth - 64) leftWidth = container.clientWidth - 64;
// 设置左边区域的宽度
left.style.width = leftWidth + 'px';
// 设备分栏竖条的left位置
resize.style.left = leftWidth;
// 设置右边区域的宽度
right.style.width = (container.clientWidth - leftWidth - 4) + 'px';
}
document.onmouseup = function(e) {
document.onmousemove = null;
document.onmouseup = null;
}
}
};