瀏覽網頁時,經常看到這樣一個功能,可以通過拖拽線條,改變左右區域大小
? ? ?在管理后臺中更為常見,菜單的寬度如果固定死,而后續新增的菜單名稱又不固定,所以很可能導致換行,樣式不太美觀,如果增加這么一個功能,效果顯而易見哦
<template><div class="page" ref="page" :style="{width: `${totalWidth}px`}"><div class="left" :style="{width: `${leftWidth}px`}"><div>這是菜單,很長很長很長...</div><div>leftWidth: {{ leftWidth }}</div></div><div class="move_line" ref="splitLine"></div><div class="right" :style="{width: `${rightWidth}px`}"><div>這是右側區域內容</div><div>rightWidth: {{ rightWidth }}</div></div></div>
</template><script>
export default {name: '',data() {return {totalWidth: 800,leftWidth: 200};},computed: {rightWidth(){return this.totalWidth - this.leftWidth - 7}},mounted() {this.handleStretch()},methods: { handleStretch(leftMinWidth = 200, rightMinWidth = 350) {// 默認左側最小200px, 右側最小350pxlet that = this// 獲取Dom節點const pageDom = this.$refs.page, moveLineDom = this.$refs.splitLinelet moveLineDomWidth = 3// 鼠標點擊, 記錄移動的開始位置moveLineDom.onmousedown = (e) => {const startX = e.clientX; // 記錄坐標起始位置console.log("start", startX)let sidebarInitWidth = that.leftWidth// 鼠標移動document.onmousemove = (e) => {// console.log("mousemove")const endX = e.clientX; // 鼠標拖動的終止位置let moveLen = sidebarInitWidth + (endX - startX); // 移動的距離 = endX - startXconst maxWidth = pageDom.clientWidth - moveLineDomWidth; // 左右兩邊區域的總寬度 = 外層容器寬度 - 中間區域拖拉框的寬度// 右邊區域最小寬度為 rightMinWidthif (moveLen > maxWidth - rightMinWidth) {moveLen = maxWidth - rightMinWidth;}// 限制左邊區域的最小寬度為 leftMinWidthif (moveLen < leftMinWidth) {moveLen = leftMinWidth;}// 更新寬度that.leftWidth = moveLen};// 鼠標松開document.onmouseup = () => {document.onmousemove = null;document.onmouseup = null;moveLineDom.releaseCapture && moveLineDom.releaseCapture(); // 鼠標捕獲釋放};moveLineDom.setCapture && moveLineDom.setCapture(); // 啟用鼠標捕獲return false;};},}
}
</script><style lang="scss" scoped>
.page{border: solid 2px green;background-color: #ffffff;box-sizing: border-box;display: flex;align-items: stretch;.move_line {width: 3px;height: calc(100vh - 48px);flex-shrink: 0;background-color: #E6EDFF;cursor: col-resize;}.move_line:hover {background-color: #409EFF;}.left, .right{padding: 20px;}
}
</style>
實現效果如下: