如何使用 HammerJs 和 Angular 创建可拖动元素
How to create a draggable element with HammerJs and Angular
我正在尝试使用 HammerJs 和 Angular 实现可拖动功能,但我的元素没有移动。打印出鼠标点但是元素没有移动
@Component({
selector: 'app-example',
styles: ['.demo-one {width:200px;height:200px;background-color: slateblue;color: #fff;}',
'.demo-one:hover {cursor:pointer}'],
template: `<div class="demo-one" [style.marginleft.px]="x" [style.margintop.px]="y"
(panstart)="onPanStart($event)" (panmove)="onPan($event)">
<div class="label">{{title}}</div>
<div class="location">({{x}}, {{y}})</div>
</div>`
})
export class ExampleComponent implements OnInit {
x = 0;
y = 0;
title = 'Drag Me!';
startX = 0;
startY = 0;
constructor() { }
ngOnInit() {
}
onPanStart(event: any): void {
this.startX = this.x;
this.startY = this.y;
}
onPan(event: any): void {
event.preventDefault();
this.x = this.startX + event.deltaX;
this.y = this.startY + event.deltaY;
}
}
我认为您应该对可拖动元素使用 position: absolute
并在拖动时设置其 left
和 top
而不是 marginleft
和 margintop
。通过这样做,元素将更自由地移动。
检查以下内容:
styles: ['.demo-one {position: absolute; width:200px;height:200px;background-color: slateblue;color: #fff;}','.demo-one:hover {cursor:pointer}']
template: `<div class="demo-one" [style.left]="x" [style.top]="y (panstart)="onPanStart($event)" (panmove)="onPan($event)">
我正在尝试使用 HammerJs 和 Angular 实现可拖动功能,但我的元素没有移动。打印出鼠标点但是元素没有移动
@Component({
selector: 'app-example',
styles: ['.demo-one {width:200px;height:200px;background-color: slateblue;color: #fff;}',
'.demo-one:hover {cursor:pointer}'],
template: `<div class="demo-one" [style.marginleft.px]="x" [style.margintop.px]="y"
(panstart)="onPanStart($event)" (panmove)="onPan($event)">
<div class="label">{{title}}</div>
<div class="location">({{x}}, {{y}})</div>
</div>`
})
export class ExampleComponent implements OnInit {
x = 0;
y = 0;
title = 'Drag Me!';
startX = 0;
startY = 0;
constructor() { }
ngOnInit() {
}
onPanStart(event: any): void {
this.startX = this.x;
this.startY = this.y;
}
onPan(event: any): void {
event.preventDefault();
this.x = this.startX + event.deltaX;
this.y = this.startY + event.deltaY;
}
}
我认为您应该对可拖动元素使用 position: absolute
并在拖动时设置其 left
和 top
而不是 marginleft
和 margintop
。通过这样做,元素将更自由地移动。
检查以下内容:
styles: ['.demo-one {position: absolute; width:200px;height:200px;background-color: slateblue;color: #fff;}','.demo-one:hover {cursor:pointer}']
template: `<div class="demo-one" [style.left]="x" [style.top]="y (panstart)="onPanStart($event)" (panmove)="onPan($event)">