ionic4-指令实现ion-fab悬浮按钮的拖拽
效果:
ion-fab拖拽效果图.gif使用:
<ion-fab style="width: 56px;height: 56px;" absolute-drag startRight="0" startTop="0" vertical="top" color="light" horizontal="end" slot="fixed">
<ion-fab-button color="light" size="small">
<ion-icon name="menu"></ion-icon>
</ion-fab-button>
<ion-fab-list>
<ion-fab-button color="light" size="small" (click)="presentPopover1($event)">
<ion-icon name="search" style="color:#3880ff"></ion-icon>
</ion-fab-button>
<ion-fab-button color="light" size="small" (click)="screenTrans()">
<ion-icon name="phone-landscape" style="color:#3880ff"></ion-icon>
</ion-fab-button>
</ion-fab-list>
</ion-fab>
在ion-fab加上:absolute-drag startRight="0" startTop="0"
实现:
1.新建指令:
ionic g directive directive/absoluteDrag
2.指令文件位置、代码为:
image.png
import { Directive, Input, ElementRef, Renderer2 } from '@angular/core';
import {DomController} from '@ionic/angular';
@Directive({
selector: '[absolute-drag]'
})
export class AbsoluteDragDirective {
@Input('startTop') startTop: any;
@Input('startRight') startRight: any;
@Input('startBottom') startBottom: any;
@Input('startLeft') startLeft: any;
constructor(public element: ElementRef, public renderer2: Renderer2, public domCtrl: DomController) {
}
ngAfterViewInit() {
this.renderer2.setStyle(this.element.nativeElement, 'position', 'absolute');
if(this.startTop)this.renderer2.setStyle(this.element.nativeElement, 'top', this.startTop + 'px');
if(this.startRight)this.renderer2.setStyle(this.element.nativeElement, 'right', this.startRight + 'px');
if(this.startBottom)this.renderer2.setStyle(this.element.nativeElement, 'bottom', this.startBottom + 'px');
if(this.startLeft)this.renderer2.setStyle(this.element.nativeElement, 'left', this.startLeft + 'px');
let hammer = new window['Hammer'](this.element.nativeElement);
hammer.get('pan').set({ direction: window['Hammer'].DIRECTION_ALL });
hammer.on('pan', (ev) => {
this.handlePan(ev);
});
}
handlePan(ev){
let fabWidth = 56,fabHeight = 56;
let newLeft = ev.center.x;
let newTop = ev.center.y;
let clientWidth = document.body.clientWidth;
let clientHeight = document.body.clientHeight;
this.domCtrl.write(() => {
if(newTop <= 0){
this.renderer2.setStyle(this.element.nativeElement, 'top', '0px');
}else if(newTop >= clientHeight-fabHeight){
this.renderer2.setStyle(this.element.nativeElement, 'bottom', '0px');
}else{
this.renderer2.setStyle(this.element.nativeElement, 'top', newTop+ 'px');
}
if(newLeft <= 0){
this.renderer2.setStyle(this.element.nativeElement, 'left', '0px');
}else if(newLeft >= clientWidth-fabWidth){
this.renderer2.setStyle(this.element.nativeElement, 'right', '0px');
}else{
this.renderer2.setStyle(this.element.nativeElement, 'left', newLeft+ 'px');
}
});
}
}
3.引用及声明指令:
import { AbsoluteDragDirective } from './directive/absolute-drag.directive';
declarations: [
AppComponent,
AbsoluteDragDirective
],
参考:ionic3入门——ion-fab悬浮按钮的拖拽,ionic指令:https://www.jianshu.com/p/017456bdad0b
注:ionic3和ionic4略有不同,稍有修改。
网友评论