1、需求:有個頁面有兩個模塊,兩個模塊里面的內容都挺多並且需要,就要一個拖拽來控制兩個模塊的占位面積了
2、思路:設置右邊模塊margin空出一塊空間放置拖拽的線,給線綁定mousedown方法,通過鼠標點擊配置onmousemove和onmouseup的方法來計算需要的參數,通過動態設置style來控制左右模塊及線的位置,當松開鼠標的時候解除onmousemove和onmouseup的方法防止占用資源
3、實現
html:(寫style要注意px這些單位容易忘記導致不會生效)
//左邊div <div class="left" ref="left" :style="leftWidth ? `width:${leftWidth}px;` : ''">//...以下省略 //右邊div <div class="right" ref="right" :style="rightWidth ? `width:${rightWidth}px;` : ''">//...以下省略 //線 <div class="line" @mousedown="dragLine" :style="`left:${moveLineLeft}px;`"></div>
線的css(scss):(拖動div時會出現選中字體現象,所以要加user-select: none;)
.line { position: fixed; width: 20px; height: calc(100% - 130px); cursor: col-resize; overflow: hidden; z-index: 4; user-select: none; &::after { content: ''; position: absolute; top: 0; bottom: 0; left: 0; right: 0; display: block; margin: auto; width: 0; border: 1px dashed #ccc; } }
js:
dragLine() { let width = this.$refs.main_box.clientWidth//獲取盒子的寬 //綁定onmousemove document.onmousemove = (e) => {//鼠標點擊拖動時 this.moveLineLeft = e.clientX } //綁定onmouseup document.onmouseup = () => {//松開鼠標時 if (this.moveLineLeft < 655) {//設置一個最小值 以下計算根據實際需求 this.leftWidth = 585 this.moveLineLeft = 695 this.rightWidth = width - 585 } else if (this.moveLineLeft > (width + 70) - 555) {//設置一個最大值 以下計算根據實際需求 this.rightWidth = 555 this.leftWidth = width - 555 this.moveLineLeft = width - 505 } else { this.leftWidth = this.moveLineLeft - 102 this.rightWidth = width - this.moveLineLeft - 142 } //解綁 document.onmousemove = null; document.onmouseup = null; } }
4、效果