自定义拖拽面板angular7_Angular Material 7拖放x和y坐标

I have a container with an element inside it. I want to be able to drag the element to another location inside the container and see the new x and y coordinates (where x=0 and y=0 is the top left corner of the container).

I have a basic stackblitz set up at https://stackblitz.com/edit/material-6-mjrhg1, but it won't show the entire event object in the console ("object too large"). In my actual application, I can look through the entire event object, but I can't find any properties describing the new x and y locations.

The basic setup is this:

style="height: 20px; width: 20px; background-color: red; z-index: 10"

cdkDrag

cdkDragBoundary=".container"

(cdkDragEnded)="onDragEnded($event)">

I have also tried some of the other events, but cdkDragEnded makes the most sense to me.

Any ideas what property to check to find the x and y coordinates, or should I be using a different event / approach?

解决方案

You can access the element that is being dragged from the source property on your CdkDragEnd event.

onDragEnded(event) {

let element = event.source.getRootElement();

let boundingClientRect = element.getBoundingClientRect();

let parentPosition = this.getPosition(element);

console.log('x: ' + (boundingClientRect.x - parentPosition.left), 'y: ' + (boundingClientRect.y - parentPosition.top));

}

getPosition(el) {

let x = 0;

let y = 0;

while(el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {

x += el.offsetLeft - el.scrollLeft;

y += el.offsetTop - el.scrollTop;

el = el.offsetParent;

}

return { top: y, left: x };

}

I have modified the stackblitz to log the x and y coordinates of the rectangle being moved here.

To solve the problem where the rectangle to be moved is contained in another element, we use the getPosition function (which has been taken from this stackoverflow post) to retrieve the top/left values of the containing element, which then lets us calculate the x/y coordinates correctly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值