【问题标题】:Angular Material 7 Drag and Drop x and y coordinatesAngular Material 7 拖放 x 和 y 坐标
【发布时间】:2019-01-14 16:19:17
【问题描述】:

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

我在https://stackblitz.com/edit/material-6-mjrhg1 设置了一个基本的 stackblitz,但它不会在控制台中显示整个事件对象(“对象太大”)。在我的实际应用中,我可以查看整个事件对象,但找不到任何描述新 x 和 y 位置的属性。

基本设置是这样的:

<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 对我来说最有意义。

知道要检查什么属性来查找 x 和 y 坐标,还是我应该使用不同的事件/方法?

【问题讨论】:

    标签: drag-and-drop angular-material angular-material-7


    【解决方案1】:

    您可以通过CdkDragEnd 事件访问从source 属性中拖动的元素。

    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 坐标here

    为了解决要移动的矩形包含在另一个元素中的问题,我们使用getPosition 函数(取自this stackoverflow 帖子)来检索包含元素的顶部/左侧值,然后让我们正确计算 x/y 坐标。

    【讨论】:

    猜你喜欢
    • 2019-05-05
    • 2012-03-11
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2016-12-15
    • 2023-03-30
    相关资源
    最近更新 更多