我正在尝试使用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;
}
}
答案 0 :(得分:1)
我认为您应该使用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)">