将div定位在另一个div的坐标上

时间:2018-01-12 11:47:00

标签: javascript css angular

我有一个div里面我有一个锚标签,点击锚标签我采取它的坐标和使用javascript我在它旁边放置另一个div。 以下是我的父母。

<div class="parent1-div>
  <div class="parent2-div>
    <div class="child-div">
      <a (click)="anchorClickEvent($event)"></a>
    </div>
  </div>
</div>

这是另一个div,我把它分开,所以它也可以在其他地方使用,

<div class="movable-div" [ngStyle]="{'left': xPosition, 'top': yPosition}">
   This div contains some crazy animation
</div>

点击活动:

anchorClickEvent(event: Event){
    this.xPos = event.currentTarget['x'] - somePx + 'px';
    this.yPos = event.currentTarget['y'] - somePx + 'px';
}

这给了我相对于整个身体的位置,但我需要'child-div'相对于'parent-div1'的位置,所以我可以将这些位置设置为'movable-div'。

赞赏输入。

1 个答案:

答案 0 :(得分:0)

解决了我的问题: 在点击事件中,我获得了锚标记的偏移量和最顶层容器的减去偏移量,即'parent1-div'。

anchorClickEvent(event: Event){
  this.xPos = Math.round(event.srcElement.getBoundingClientRect().left) - Math.round(event.srcElement.closest('.parent1-div').getBoundingClientRect().left) + 'px';
  this.yPos = Math.round(event.srcElement.getBoundingClientRect().top) - Math.round(event.srcElement.closest('.parent1-div').getBoundingClientRect().top) + 'px';
}

并将这些样式动态添加到'movable-div'元素,该元素相对于body是绝对位置。

<div class="movable-div" [ngStyle]="{'left': xPos, 'top': yPos}">
  This div contains some crazy animation
</div>