实现最终效果直接上代码:
html:
<div className={styles.Home} id='box'>
<div className={styles.Left} id='left'>
放入左侧内容
</div>
<div className={styles.Middle} id="middle" ></div>
<div className={styles.Right} id='right'>
右侧内容
</div>
</div>
css:
.Home {
width: 100%;
height: 100%;
display: flex;
justify-content: space-between;
.Left {
width: 240px;
background-color: #d8e4eb;
}
.Right {
width: 100%;
position: relative;
background-color: #fff;
padding: 20px;
}
.Middle {
cursor: col-resize;
height: 100%;
position: relative;
width: 2px;
border-left: 1px solid #8f949a;
}
.Middle:hover {
border: 1px solid #8f949a;
background-color: #8f949a;
}
.Middle:active {
border: 1px solid #8f949a;
background-color: #8f949a;
}
}
js:
componentDidMount() {
window.onload = function () {
let resize = document.getElementById("middle");
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 < 59) moveLen = 59;
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;
};
};
}
遇到的问题:
如果左边或右边div标签的旁边还存在其他标签,如图:
在拖拽的时候光标就会自动多跳一段宽度,这个宽度正好就是侧边导航栏的宽度。
解决办法:
第一种:去掉左侧导航栏(这样肯定没问题)
第二种:获取左侧导航栏的宽度并减掉它(不是像素宽度)
这样应该就没问题了,之前碰到这个需求,到网上找了点资料,然后自己整理了一下加深印象,如有问题欢迎指正!