上篇博客分享了修改左右两侧元素的宽度【vue实现拖拽修改左右两侧元素宽度】,在实践中还会遇到仅修改某一单一元素宽度,以下是实现方法:
实现效果
HTML
<div class="container">
测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试
<div ref="containerDom" class="right">
<div style="display: flex; height: 100%">
<div class="resize" ref="resizeDom">⋮</div>
<div style="flex: 1">右侧测试</div>
</div>
</div>
</div>
实现方法
dragControllerDiv() {
const resizeDom = this.$refs.resizeDom;
const containerDom = this.$refs.containerDom;
resizeDom.style.cursor = "e-resize";
resizeDom.onmousedown = (e) => {
document.onselectstart = function () {
return false;
}; //解决拖动会选中文字的问题
// 鼠标按下,计算当前元素距离可视区的距离
const disX = e.clientX;
const w = containerDom.clientWidth;
const minW = 300;
const maxW = 1800;
var nw;
document.onmousemove = (e) => {
// 通过事件委托,计算移动的距离
const l = e.clientX - disX;
// 改变当前元素宽度,不可超过最小最大值
nw = w - l;
nw = nw < minW ? minW : nw;
nw = nw > maxW ? maxW : nw;
containerDom.style.width = `${nw}px`;
};
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
};
};
}
CSS
.container {
position: relative;
}
.resize {
cursor: col-resize;
position: relative;
top: 45%;
left: -15px;
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;
}
.right {
width: 400px;
height: 100vh;
border: 1px solid #ccc;
position: fixed;
top: 0;
right: 0;
box-shadow: 4px 4px 2px 8px #f5f5f5;
background: #fff;
}