我在drag.ts>上有一些关于plunker的代码。 http://plnkr.co/edit/PITLKzBB6YXobR1gubOw?p=preview要求拖放(它仅适用于单独的窗口预览)
import {Component, OnInit, ElementRef, Renderer} from '@angular/core'
@Component({
selector: 'my-drag',
template: `
<div class="drag"
draggable="true"
(dragstart)="onDragStart($event)"
(dragend)="onDragEnd($event)"
(drag)="onDrag($event)">
drag
</div>
`,
styles: ['.drag {width: 50px; height: 50px; border: 1px solid black; background-color: red;}']
})
export class DragComponent implements OnInit {
private dx: number = 0;
private dy: number = 0;
constructor(private el: ElementRef, private renderer: Renderer) { }
ngOnInit() {
this.renderer.setElementStyle(this.el.nativeElement, 'position', 'absolute');
}
onDragStart(event: MouseEvent) {
this.dx = event.x - this.el.nativeElement.offsetLeft;
this.dy = event.y - this.el.nativeElement.offsetTop;
}
onDrag(event: MouseEvent) {
this.move(event.x, event.y);
this.renderer.setElementAttribute(this.el.nativeElement, 'draggable', 'false');
}
onDragEnd(event: MouseEvent) {
this.dx = 0;
this.dy = 0;
}
move(x: number, y: number) {
if (!x || !y) return;
this.renderer.setElementStyle(this.el.nativeElement, 'top', (y - this.dy) + 'px');
this.renderer.setElementStyle(this.el.nativeElement, 'left', (x - this.dx) + 'px');
}
}
以及它的一些问题:
全部谢谢!
答案 0 :(得分:1)
您可以将原生拖动图像设置为透明图像以删除重复。
onDragStart(event: MouseEvent) {
var dragImgEl = document.createElement('img');
dragImgEl.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; // Creates a minimal transparent image
event.dataTransfer.setDragImage(dragImgEl, 0, 0);
this.dx = event.x - this.el.nativeElement.offsetLeft;
this.dy = event.y - this.el.nativeElement.offsetTop;
}
你可以通过玩不透明游戏来实现类似的东西,但我怀疑他们可能是跨浏览器麻烦(tm)。
要使光标显示为禁用圆圈以外的其他内容,您可以在其自身上设置moveEffect。
...
<div class="drag"
draggable="true"
(dragstart)="onDragStart($event)"
(dragend)="onDragEnd($event)"
(drag)="onDrag($event)"
(dragover)="ondragover($event)">
drag
</div>
...
onDragStart(event: MouseEvent) {
..
event.dataTransfer.effectAllowed = 'move';
...
}
ondragover(mouseEv: MouseEvent){
mouseEv.dataTransfer.effectAllowed = 'move';
mouseEv.preventDefault();
}
这是一个有趣的演示:http://plnkr.co/edit/cGKcjxJGUKlWOC9GFyaJ?p=preview