Angular Material 7 Drag and Drop x and y coordinates

狂风中的少年 提交于 2019-12-08 14:02:30

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!