import { Directive, ElementRef, HostListener, Renderer2, OnInit, Input } from '@angular/core'; /** * 待完善,有问题20190709 */ @Directive({ selector: '[farrisSidebarResizeable]', }) export class FarrisSidebarDragableDirective implements OnInit { private selfEl: HTMLElement; private mainEl: HTMLElement; private isDown = false; private offsetX = 0; private offsetY = 0; @Input() farrisSidebarResizeable: boolean; constructor( private el: ElementRef, private rd: Renderer2 ) { } ngOnInit() { this.selfEl = this.el.nativeElement; this.mainEl = this.selfEl.querySelector('.f-sidebar-main'); } //处于边缘才能拖动宽度 isEdge(event: any): boolean { if (this.hasClass('f-sidebar-show', this.selfEl) && this.hasClass('f-sidebar-pos-right', this.selfEl)) { if (event.clientX - this.mainEl.getBoundingClientRect().left < 8) { return true; } else { return false; } } if (this.hasClass('f-sidebar-show', this.selfEl) && this.hasClass('f-sidebar-pos-left', this.selfEl)) { if (this.mainEl.getBoundingClientRect().right - event.clientX < 8) { return true; } else { return false; } } } //某个元素是否有某个class hasClass(cls: string, element: HTMLElement) { if (cls.length === 0 || !element) { return; } return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1; } //鼠标点击按下 @HostListener('mousedown', ['$event']) onMousedown(event: any) { if(this.farrisSidebarResizeable !== true){ return; } if (this.isEdge(event)) { this.isDown = true; } } //移动侧边栏边缘,鼠标变成可拖拽效果 @HostListener('document:mousemove', ['$event']) onMousemove(event: any) { if(this.farrisSidebarResizeable !== true){ return; } if (this.isEdge(event)) { this.rd.setStyle(this.selfEl, 'cursor', 'e-resize'); } else { this.rd.setStyle(this.selfEl, 'cursor', 'default'); } if (this.isDown) { this.offsetX = this.hasClass('f-sidebar-pos-left', this.selfEl) ? this.mainEl.getBoundingClientRect().right - event.clientX : event.clientX - this.mainEl.getBoundingClientRect().left; this.rd.setStyle(this.mainEl, 'width', (this.mainEl.offsetWidth - this.offsetX) + 'px'); } } // 鼠标点击离开 @HostListener('document:mouseup', ['$event']) onMouseup(event: any) { if(this.farrisSidebarResizeable !== true){ return; } if (this.isDown) { this.isDown = false; } } }