25-vue中實現拖動調整左右兩側盒子的寬度
阿新 • • 發佈:2022-04-12
這裡是直接完整一個元件,路由引入即可看到效果。
<template>
<div class="box" ref="box">
<div class="left">
<!--左側div內容-->
<h1>到了時間你就一定要上場</h1>
<h1>當意識到達,那就必須上岸</h1>
</div>
<div class="resize" title="收縮側邊欄"></div>
<div class="mid">
<!--右側div內容-->
<h1>我希望我希望的有希望</h1>
<h1>想著光向著光</h1>
</div>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
dragControllerDiv() {
var resize = document.getElementsByClassName("resize")[0];
var left = document.getElementsByClassName("left");
var mid = document.getElementsByClassName("mid");
var box = document.getElementsByClassName("box")[0];
// 滑鼠按下事件
resize.onmousedown = function (e) {
//顏色改變提醒
resize.style.background = "#818181";
var startX = e.clientX;
resize.left = resize.offsetLeft;
// 滑鼠拖動事件
document.onmousemove = function (e) {
var endX = e.clientX;
var moveLen = resize.left + (endX - startX); // (endx-startx)=移動的距離。resize.left+移動的距離=左邊區域最後的寬度
var maxT = box.clientWidth - resize.offsetWidth; // 容器寬度 - 左邊區域的寬度 = 右邊區域的寬度
if (moveLen < 32) moveLen = 32; // 左邊區域的最小寬度為32px
if (moveLen > maxT - 150) moveLen = maxT - 150; //右邊區域最小寬度為150px
resize.style.left = moveLen; // 設定左側區域的寬度
for (let j = 0; j < left.length; j++) {
left[j].style.width = moveLen + "px";
mid[j].style.width = box.clientWidth - moveLen - 10 + "px";
}
};
// 滑鼠鬆開事件
document.onmouseup = function () {
//顏色恢復
resize.style.background = "#d6d6d6";
document.onmousemove = null;
document.onmouseup = null;
resize.releaseCapture && resize.releaseCapture(); //當你不在需要繼續獲得滑鼠訊息就要應該呼叫ReleaseCapture()釋放掉
};
resize.setCapture && resize.setCapture(); //該函式在屬於當前執行緒的指定窗口裡設定滑鼠捕獲
return false;
};
},
},
mounted() {
this.dragControllerDiv();
},
};
</script>
<style scoped>
/* 拖拽相關樣式 */
/*包圍div樣式*/
.box {
width: 100%;
height: 50vh;
margin: 5vh 0px;
overflow: hidden;
box-shadow: -1px 9px 10px 3px rgba(0, 0, 0, 0.11);
}
/*左側div樣式*/
.left {
width: calc(32% - 10px); /*左側初始化寬度*/
height: 100%;
background: #ffffff;
float: left;
}
/*拖拽區div樣式*/
.resize {
cursor: col-resize;
float: left;
position: relative;
top: 45%;
background-color: #d6d6d6;
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;
}
/*右側div'樣式*/
.mid {
float: left;
width: 68%; /*右側初始化寬度*/
height: 100%;
background: #fff;
box-shadow: -1px 4px 5px 3px rgba(0, 0, 0, 0.11);
}
</style>