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、效果