【问题标题】:Positioning a div at co-ordinates of another div将 div 定位在另一个 div 的坐标处
【发布时间】:2018-06-21 21:09:15
【问题描述】:

我有一个 div,里面有一个锚标记,单击锚标记时,我获取它的坐标并使用 javascript 我在它旁边放置另一个 div。 下面是我的父 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'。

感谢您的意见。

【问题讨论】:

  • 真正的问题是什么?
  • 整个DOM结构不清楚。你的div.movable-div 放在哪里?

标签: javascript css angular


【解决方案1】:

解决了我的问题: 在点击事件中,我得到了锚标记的偏移量并减去了最顶层容器的偏移量,即“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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 2010-10-25
    相关资源
    最近更新 更多