最近在使用vue3的时候,需要完成一个需求,实现左右div可以拖拽调整宽度,类似于这样
借鉴(vue中实现拖动调整左右两侧div的宽度 - 掘金 (juejin.cn))简单记录一下完成这个功能
直接上代码吧😁
html代码
<div class="box" ref="box">
<div class="left">
<!--左侧div内容-->
</div>
<div class="resize" title="收缩侧边栏">⋮</div>
<div class="right">
<!--右侧div内容-->
</div>
</div>
Js代码
<script>
import { defineComponent, reactive, toRefs,onMounted } from "vue";
export default defineComponent({
setup() {
const state = reactive({
activeTabs: 1,
});
onMounted(() => {
dragControllerDiv()
})
function dragControllerDiv(){
let resize = document.getElementsByClassName("resize");
let boxDom = document.getElementsByClassName('box')
let leftDom = document.getElementsByClassName('left')
let rightDom = document.getElementsByClassName('right')
for (let i = 0; i < resize.length; i++) {
/*鼠标 按下拖拽区 */
resize[i].onmousedown = function(e){
// 拖拽区 变色
resize[i].style.background = "#818181";
// 拖拽区 开始的距离 403
var startX = e.clientX;
// 左边大小 放入 resize
resize[i].left = resize[i].offsetLeft;
/* 鼠标拖拽 */
document.onmousemove = function(ee) {
// 拖拽区 结束的距离
var endX = ee.clientX;
// 移动的距离 (endx-startx)=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
let leftWidth = resize[i].left + (endX - startX)
// 右边最大宽度
let maxWidth = boxDom[i].clientWidth - resize[i].offsetWidth;
/* 设置 左边 最小值 */
if (leftWidth < 400) leftWidth = 400
if (leftWidth > maxWidth - 400) leftWidth = maxWidth - 400
// 设置拖拽条 距离左侧区域的宽度
resize[i].style.left = leftWidth;
// 设置 左边宽度
leftDom[i].style.width = leftWidth + 'px';
// 设置右边宽度
rightDom[i].style.width = (boxDom[i].clientWidth - leftWidth - 10) + 'px';
}
/* 鼠标松开 */
document.onmouseup = function() {
// 取消事件
document.onmousemove = null;
document.onmouseup = null;
// 恢复颜色
resize[i].style.background = "#d6d6d6";
}
}
return false;
}
}
return {
...toRefs(state),
};
},
});
</script>
css样式
<style lang="scss" scoped>
.box{
width: 100%;
height: 100%;
display: flex;
}
.left{
width: 60%;
background: #40e0cf;
}
.right{
width: 40%;
background: #7fbcff;
}
/*拖拽区div样式*/
.resize {
cursor: col-resize;
float: left;
position: relative;
top: 45%;
background: blue;
border-radius: 5px;
margin-top: -10px;
width: 10px;
height: 50px;
background-size: cover;
background-position: center;
/*z-index: 99999;*/
font-size: 32px;
color: white;
}
/*拖拽区鼠标悬停样式*/
.resize:hover {
color: #444444;
}
</style>
以上代码就是实现div的左右拖拽,嘿嘿嘿