前端开发时通常会遇到拖拽修改两侧宽度的需求,以下是实现方法
实现效果
HTML
<div class="box" ref="box">
<div class="left" ref="left">左边测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试</div>
<div class="resize" ref="resizeDom">⋮</div>
<div class="mid" ref="mid">右边测试</div>
</div>
实现方法
dragControllerDiv() {
var resize = document.getElementsByClassName("resize");
var left = document.getElementsByClassName("left");
var mid = document.getElementsByClassName("mid");
var box = document.getElementsByClassName("box");
for (let i = 0; i < resize.length; i++) {
// 鼠标按下事件
resize[i].onmousedown = (e) => {
//颜色改变提醒
resize[i].style.background = "#818181";
var startX = e.clientX;
resize[i].left = resize[i].offsetLeft;
// 鼠标拖动事件
document.onmousemove = (e) => {
var endX = e.clientX;
var moveLen = resize[i].left + (endX - startX); // (endx-startx)=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
var maxT = box[i].clientWidth - resize[i].offsetWidth; // 容器宽度 - 左边区域的宽度 = 右边区域的宽度
if (moveLen < 300) moveLen = 300; // 左边区域的最小宽度为300px
if (moveLen > maxT - 300) moveLen = maxT - 300; //右边区域最小宽度为300px
resize[i].style.left = moveLen; // 设置左侧区域的宽度
for (let j = 0; j < left.length; j++) {
left[j].style.width = moveLen + "px";
mid[j].style.width =
box[i].clientWidth - moveLen - 10 + "px";
}
};
// 鼠标松开事件
document.onmouseup = (evt) => {
//颜色恢复
resize[i].style.background = "#d6d6d6";
document.onmousemove = null;
document.onmouseup = null;
resize[i].releaseCapture && resize[i].releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
};
resize[i].setCapture && resize[i].setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
return false;
};
}
},
CSS
.box {
width: 100%;
height: 100vh;
overflow: hidden;
box-shadow: -1px 9px 10px 3px rgba(0, 0, 0, 0.11);
display: flex;
}
.left {
width: calc(32% - 10px);
height: 100%;
background: #ffffff;
position: relative;
}
/*拖拽区div样式*/
.resize {
cursor: col-resize;
position: relative;
top: 45%;
background-color: #d6d6d6;
border-radius: 5px;
margin-top: -10px;
width: 10px;
height: 50px;
background-size: cover;
background-position: center;
font-size: 32px;
color: white;
}
/*拖拽区鼠标悬停样式*/
.resize:hover {
color: #444444;
}
/*右侧div'样式*/
.mid {
width: 68%;
height: 100%;
background: #fff;
box-shadow: -1px 4px 5px 3px rgba(0, 0, 0, 0.11);
}