鼠标左右拖动改变左右盒子大小功能。
<div id='box' className='box'>
<div id='left' className='left'>左边盒子</div>
<div id='resize' className='resize' />
<div id='right' className='right'>右边盒子</div>
</div>
.box {
display: flex;
width: 100%;
height: 300px;
background: #fff;
.left {
width: 300px;
text-align: center;
}
.right {
flex: 1;
text-align: center;
}
.resize{
cursor: w-resize;
position: relative;
border: 1px solid #cecece;
}
}
window.onload = function () {
let resize = document.getElementById("resize");
let left = document.getElementById("left");
let right = document.getElementById("right");
let box = document.getElementById("box");
resize.onmousedown = function (e) {
let startX = e.clientX;
resize.left = resize.offsetLeft;
document.onmousemove = function (e) {
let endX = e.clientX;
let moveLen = resize.left + (endX - startX);
let maxT = box.clientWidth - resize.offsetWidth;
if (moveLen > maxT - 500) moveLen = maxT - 500;
resize.style.left = moveLen;
left.style.width = moveLen + "px";
right.style.width = (box.clientWidth - moveLen - 5) + "px";
}
document.onmouseup = function (evt) {
evt.stopPropagation()
document.onmousemove = null;
document.onmouseup = null;
resize.releaseCapture && resize.releaseCapture();
}
resize.setCapture && resize.setCapture();
return false;
}
}