如何在Angular 2+中通过鼠标拖拽实现div垂直可调整大小功能
Angular 2+ 实现div垂直可调整大小的完整方案
核心交互逻辑拆解
整个调整功能的触发链路严格匹配动态绑定事件的实现思路,不需要全局常驻事件监听:
- 仅在调整手柄元素上监听
mousedown事件,触发时记录鼠标按下瞬间的垂直坐标、目标div的初始高度,将组件状态标记为「调整中」 - 调整状态激活后,临时在
document对象上挂载mousemove、mouseup全局事件,解决鼠标移出调整手柄后无法持续捕获移动动作的问题 mousemove触发时计算鼠标位移差值,同步更新目标div的高度样式mouseup触发时立刻移除全局挂载的事件,将组件状态重置为「非调整中」,避免无效的事件触发与性能损耗
现有初始代码的优化方向
原有代码的两处关键调整点:
- 原代码将鼠标事件绑定在整个可调整div容器上,实际交互应仅绑定在调整手柄元素上,避免点击容器内容区域误触发调整逻辑
- 原生事件绑定需要配套组件销毁时的解绑逻辑,否则会造成内存泄漏
补全后的完整实现代码
组件HTML(补充调整手柄的模板引用)
<div #resizable class="resizable"> <div #resizer class="resizer">RESIZE</div> </div>
组件TypeScript逻辑
import { Component, ElementRef, ViewChild, OnDestroy, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements AfterViewInit, OnDestroy { @ViewChild('resizable') resizable!: ElementRef<HTMLDivElement>; @ViewChild('resizer') resizer!: ElementRef<HTMLDivElement>; // 调整过程中的临时状态 private startY = 0; private startHeight = 0; private isResizing = false; // 预存事件绑定引用,方便后续精准解绑 private boundMousemove = this.onMousemove.bind(this); private boundMouseup = this.onMouseup.bind(this); ngAfterViewInit() { // 仅给调整手柄绑定按下事件 this.resizer.nativeElement.addEventListener('mousedown', this.onMousedown.bind(this)); } // 调整手柄按下鼠标的处理逻辑 private onMousedown(e: MouseEvent) { e.preventDefault(); // 记录调整初始状态 this.isResizing = true; this.startY = e.clientY; this.startHeight = this.resizable.nativeElement.offsetHeight; // 动态挂载全局移动、松开事件 document.addEventListener('mousemove', this.boundMousemove); document.addEventListener('mouseup', this.boundMouseup); } // 鼠标移动的处理逻辑 private onMousemove(e: MouseEvent) { if (!this.isResizing) return; // 计算垂直位移差值 const deltaY = e.clientY - this.startY; // 同步更新div高度,可根据业务需要追加最小/最大高度限制 this.resizable.nativeElement.style.height = `${this.startHeight + deltaY}px`; } // 鼠标松开的处理逻辑 private onMouseup() { this.isResizing = false; // 动态移除全局事件,结束调整流程 document.removeEventListener('mousemove', this.boundMousemove); document.removeEventListener('mouseup', this.boundMouseup); } ngOnDestroy() { // 组件销毁时清理残留事件绑定,防止内存泄漏 if (this.isResizing) { document.removeEventListener('mousemove', this.boundMousemove); document.removeEventListener('mouseup', this.boundMouseup); } } }
配套基础样式(保证交互体验)
.resizable { position: relative; width: 300px; min-height: 200px; border: 1px solid #eee; overflow: auto; } .resizer { position: absolute; bottom: 0; left: 0; width: 100%; height: 8px; background: #f5f5f5; cursor: ns-resize; user-select: none; }
可选优化方向
- 在高度计算环节追加边界判断,限制div的最小、最大调整高度,避免元素被拖拽到影响页面布局的尺寸
- 追加触屏事件适配,将
mousedown/mousemove/mouseup替换为对应的touchstart/touchmove/touchend事件,从Touch对象中取垂直坐标值即可兼容移动端
内容的提问来源于stack exchange,提问作者Łukasz
相关产品推荐
相关产品推荐

