javascript - 角度拖放图标到画布
解决方案
我们的“字段”是带有文本的对象,顶部和左侧。所以,你可以创建一个函数
changePosition(event:CdkDragEnd<any>,field)
{
console.log(field)
field.top=+field.top.replace('px','')+event.distance.y+'px'
field.left=+field.left.replace('px','')+event.distance.x+'px'
}
然后你调用 .html
<div *ngFor="let field of fields;" cdkDrag (cdkDragEnded)="changePosition($event,field)"
style="position:absolute;z-index:10" [style.top]="field.top" [style.left]="field.left">
{{field.text}}
</div>
更新了问题,因为 Ananthakrishna 让我知道,您可以将拖放区中的一个元素拖出“dop-zone”
我们需要使用事件cdkDragDropped
<div *ngFor="let field of fields;" cdkDrag
(cdkDragDropped)="changePosition($event,field)"
style="position:absolute;z-index:10"
[style.top]="field.top"
[style.left]="field.left">
{{field.text}}
</div>
并且,在我们的函数 changePosition 中“检查”是否在 droppend 里面。我使用相关元素的 getBoundingClientRect :
changePosition(event:CdkDragDrop<any>,field)
{
const rectZone=this.dropZone.nativeElement.getBoundingClientRect()
const rectElement=event.item.element.nativeElement.getBoundingClientRect()
let top=+field.top.replace('px','')+event.distance.y
let left=+field.left.replace('px','')+event.distance.x
const out=top<0 || left<0 ||
(top>(rectZone.height-rectElement.height)) ||
(left>(rectZone.width-rectElement.width))
if (!out) //If is inside
{
field.top=top+'px'
field.left=left+'px'
}
else{ //we can do nothing
this.fields=this.fields.filter(x=>x!=field) //or eliminate the object
}
}
查看分叉的stackblitz
推荐阅读
- windows - 有没有办法使用 NPS / RADIUS 服务器进行 Windows 桌面身份验证?计算机可以通过 NPS 而不是正常登录来对自身进行 RDP 吗?
- c# - WebService 中的 ICollection 属性导致“远程服务器返回错误:(400) 错误请求”
- c++ - 加入 std::ranges::single_views 意外结果
- security - EQL 序列以匹配不存在的事件
- pytube - 如何使用 pytube 获取视频的文件大小?
- python - 使用 Selenium 登录 AngularJS 站点
- html - 更改 HTML/CSS 文件中的字体
- wordpress - 安装 Yoast 插件后 Elementor Elements 未加载
- apache-spark - 从 Azure 数据工厂提交 spark 应用(AKS 上的 Spark)
- android - 如何使用 android 复制自动热点功能?