如何用HammerJs和Angular创建一个可拖动的元素

时间:2018-02-06 22:34:16

标签: angular gesture hammer.js

我正在尝试使用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;
  }
}

1 个答案:

答案 0 :(得分:1)

我认为您应该使用position: absolute作为可拖动元素,并在拖动它时设置其lefttop而不是marginleftmargintop。通过这样做,元素将更自由地移动。

检查以下内容:

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)">