通过拖拽调整div宽度
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、效果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」