Angular Material 7拖放x和y坐标 [英] Angular Material 7 Drag and Drop x and y coordinates

查看:182
本文介绍了Angular Material 7拖放x和y坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个容器,里面有一个元素.我希望能够将元素拖动到容器内的另一个位置,并查看新的x和y坐标(其中x = 0和y = 0是容器的左上角).

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

我在 https://stackblitz.com/edit/material- 6-mjrhg1 ,但不会在控制台中显示整个事件对象(对象太大").在我的实际应用程序中,我可以浏览整个事件对象,但是找不到描述新的x和y位置的任何属性.

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.

基本设置是这样:

<div style="height: 200px; width=200px; background-color: yellow" class="container">
  <div 
    style="height: 20px; width: 20px; background-color: red; z-index: 10" 
    cdkDrag 
    cdkDragBoundary=".container"
    (cdkDragEnded)="onDragEnded($event)">
  </div>
</div>

我也尝试了其他一些事件,但是cdkDragEnded对我来说最有意义.

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

有什么想法可以检查要查找x和y坐标的属性,还是应该使用其他事件/方法?

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

推荐答案

您可以访问CdkDragEnd事件上从source属性拖动的元素.

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 };
}

我修改了stackblitz以记录要移动的矩形的x和y坐标此处.

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

要解决要移动的矩形包含在另一个元素中的问题,我们使用getPosition函数(该函数取自

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.

这篇关于Angular Material 7拖放x和y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆