【发布时间】:2019-01-23 10:09:38
【问题描述】:
在拖动项目时使用*cdkDragPreview可以改变位置吗?现在我在拖动时所做的样式总是出现在光标的右下角。我想把它放在左上角。
有什么帮助吗?
【问题讨论】:
标签: angular angular-material angular-cdk
在拖动项目时使用*cdkDragPreview可以改变位置吗?现在我在拖动时所做的样式总是出现在光标的右下角。我想把它放在左上角。
有什么帮助吗?
【问题讨论】:
标签: angular angular-material angular-cdk
是的,您可以订阅 cdkDragMoved 并抵消您的 *cdkDragPreview。
示例
以下示例将在 x 和 y 轴上偏移 100px 的预览
<div cdkDrag
[id]="storageNode.barcode"
[cdkDragData]="storageNode"
[cdkDragDisabled]="dragDisabled"
(cdkDragMoved)="onDragMove($event)">
<div title="Drag this entity and its children"
class="entity-drag-handle"
cdkDragHandle>
{{storageNode.barcode}}
<mat-icon *ngIf="!dragDisabled">
drag_indicator
</mat-icon>
</div>
<div
[id]="storageNode.barcode + 'preview'"
[ngStyle]="{'background-color': this.getBackgroundColor(0.6)}"
class="entity-drag-preview"
*cdkDragPreview>
<h4>{{storageNode.barcode}}</h4>
<p>{{formattedDescription}}</p>
</div>
</div>
请记住,这使用了 typescript 3.7 的功能,这些功能在旧版本上不起作用
public onDragMove(event: CdkDragMove<StorageEntity>): void {
const nodeMovePreview = new ElementRef<HTMLElement>(document.getElementById(this.storageNode.barcode + 'preview'));
const xPos = event.pointerPosition.x - 100;
const yPos = event.pointerPosition.y - 100;
if (nodeMovePreview?.nativeElement) {
nodeMovePreview.nativeElement.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
}
}
【讨论】:
if (nodeMovePreview?.nativeElement) { 更改为 if (nodeMovePreview && nodeMovePreview.nativeElement) {。
[HTML]
<div
cdkDrag
(cdkDragReleased)="cdkDragReleased($event, i)"
(cdkDragDropped)="cdkDragDropped($event)">
<div class="my-placeholder" *cdkDragPlaceholder></div>
<div class="my-preview" *cdkDragPreview></div>
</div>
[CSS]
.my-placeholder {
background-color: #000;
}
.my-preview {
transform: scale(0.7) translate(-200px, -100px);
}
我在 .my-preview 中使用 translate 将项目放置在 x 轴和 y 轴上,然后使用比例缩小以使其看起来更小
【讨论】: