版本
“@angular/core”: “~10.0.3”
“ng-zorro-antd”: “^10.2.2”
实现思路
可通过自定义指令,设置一个元素定位在th上,拖动该元素,存储鼠标按下时刻的列宽和鼠标事件的screenX值记为oldScreenX,鼠标move事件是newScreenX,得到移动的距离newScreenX - oldScreenX
dynamic-column-width.directive.ts
import { Directive, ElementRef, OnInit } from '@angular/core';
import { fromEvent, Observable } from 'rxjs';
@Directive({
selector: '[appDynamicColumnWidth]'
})
export class DynamicColumnWidthDirective implements OnInit {
private mousedown$: Observable<any>;
private mousemove$: Observable<any>;
private mouseup$: Observable<any>;
private down = false; // 是否按下
private lastX: number;
private lastWidth: number;
constructor(private el: ElementRef) { }
ngOnInit(): void {
// 创建拖动定位按钮
const span = document.createElement('span');
span.className = 'resize-bar';
this.el.nativeElement.style.position = 'relative'
this.el.nativeElement.appendChild(span);
this.mousedown$ = fromEvent(span, 'mousedown');
this.mousemove$ = fromEvent(document, 'mousemove');
this.mouseup$ = fromEvent(document, 'mouseup');
this.mousedown$
.subscribe((event: MouseEvent) => {
this.down = true;
this.lastX = event.screenX;
this.lastWidth = this.el.nativeElement.offsetWidth;
})
this.mousemove$
.subscribe(event => {
if (this.down) {
this.el.nativeElement.style.width = event.screenX - this.lastX + this.lastWidth + 'px';
}
})
this.mouseup$
.subscribe(event => {
this.down = false;
})
}
}
应用在html上
<nz-table #nzTable id="table" [nzData]="listOfData" >
<thead>
<tr>
<th nzWidth="160px" appDynamicColumnWidth data-index="0">Name</th>
<th nzWidth="160px" appDynamicColumnWidth>Age</th>
<th appDynamicColumnWidth>Address</th>
<th appDynamicColumnWidth>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of nzTable.data">
<td>{{data.name}}</td>
<td>{{data.age}}</td>
<td>{{data.address}}</td>
<td><a>Delete</a></td>
</tr>
</tbody>
</nz-table>
style.less
.resize-bar {
width: 20px;
height: 55px;
background-color: rgba(255,0,0,0.5);
position: absolute;
right: -10px;
top: 0;
cursor: col-resize;
}
效果图
红色的块鼠标划上就有可拖动箭头
后记
在公司项目里,设置th的宽度有坑。设置了nzWidth属性的列,怎么设置th.style.width都没有效果;需要去设置nztable默认渲染出来的<col>
元素的宽度,在th上增加data-index属性,获取table下的col,和th按照索引对应,设置col可实现自由伸缩列宽
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。