项目需要,花一天时间研究写的东东,记录备用
效果图

首先实现一个分隔组件
divider.component.ts
import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';
@Component({
selector: 'app-divider',
templateUrl: './divider.component.html',
styleUrls: ['./divider.component.less']
})
export class DividerComponent implements OnInit {
/** 鼠标按下时坐标 */
downPosition: { x: number, y: number };
/** 左边元素的大小 */
leftSize: { width: number, height: number };
/** 右边元素的大小 */
rightSize: { width: number, height: number };
/** 鼠标是否按下 */
isMouseDown = false;
/** 左边元素 */
@Input() leftEle;
/** 右边元素 */
@Input() rightEle;
/** 分隔组件 */
@ViewChild('divider', { static: false }) divider: ElementRef;
constructor() { }
ngOnInit(): void {
// 鼠标移动事件监听
document.onmousemove = (ev: MouseEvent) => {
if (this.isMouseDown) { // 如果鼠标是按下状态
const width: number = this.leftSize.width + this.rightSize.width; // 计算左右元素宽度和
const offsetX: number = ev.x - this.downPosition.x; // 计算鼠标相对偏移量
const leftWidth = (this.leftSize.width + offsetX) * 100 / width; // 计算左元素的宽度占比
const rightWidth = (this.rightSize.width - offsetX) * 100 / width; // 计算右元素的宽度占比
this.leftEle.style.width = 'calc(' + leftWidth + '% - 5px)'; // 设置左元素的宽度
this.rightEle.style.width = 'calc(' + rightWidth + '% - 5px)'; // 设置右元素的宽度
}
return false; // 必须返回false,否则会触发系统事件,导致功能异常
};
// 鼠标按下事件监听
document.onmousedown = (ev: MouseEvent) => {
if (this.divider.nativeElement === ev.target) { // 如果对象是分隔组件
this.downPosition = { x: ev.x, y: ev.y }; // 记录下鼠标坐标
this.leftSize = { width: this.leftEle.offsetWidth, height: this.leftEle.offsetHeight }; // 获取左元素大小
this.rightSize = { width: this.rightEle.offsetWidth, height: this.rightEle.offsetHeight }; // 获取右元素大小
this.isMouseDown = true; // 鼠标按下状态设置为true
}
};
// 鼠标松开事件监听
document.onmouseup = (ev: MouseEvent) => {
this.isMouseDown = false; // 鼠标按下状态设置为false
};
}
}
divider.component.html
<div #divider></div>
divider.component.less
div {
height: 100%;
width: 10px;
background-color: green;
float: left;
}
使用:
<div class="parent">
<div #leftdiv class="div1"></div>
<app-divider [leftEle]="leftdiv" [rightEle]="rightdiv"></app-divider>
<div #rightdiv class="div3"></div>
</div>
网友评论