Javascript / 根据另一个元素的位置定位一个元素

Javascript / Positioning an element according to another element's position

我希望我的 div(默认情况下使用 style="display: none; position: absolute",它仅在单击单元格时可见)显示在 [=22] 中单击单元格左侧的 30px =]. addevent 代表我的 div,我想将 30px 放在单元格的左边。因此,我希望我的 div 出现在被单击单元格左侧的 30px 左侧。我做错了什么?

var cell = document.getElementsByTagName('td');
for (var i=0; i<cell.length; i++) {

cell[i].onclick = function() {

var data = this.getAttribute('data-cell');
editEvent = document.getElementById('addevent');
editEvent.style.cssText ='display: block;';
this.style.position = 'relative';

var rect = this.getBoundingClientRect();
editEvent.style.left = rect.left + 30;
editEvent.getElementsByTagName('input')[3].value = data;
};

正如我在评论中所说,这可能是统一错误。看例子:

var $floating = document.querySelector('.floating-div');
var $contentDivs = document.querySelectorAll('.content-div');

for (var i = $contentDivs.length; i--;) {
  $contentDivs[i].addEventListener('click', function () {
    var rect = this.getBoundingClientRect();

    $floating.style.top = rect.top - 30 + 'px';
    $floating.style.left = rect.left - 30 + 'px';
    $floating.classList.add('show');
  });
}
.content-div {
  border: solid 1px black;
  position: relative;
  width: 120px;
  top: 120px;
  left: 120px;
  float: left;
}

.floating-div {
  border: solid 1px red;
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;

  transition: opacity .2s ease, left .1s ease;
}

.floating-div.show {
  opacity: 1;
}
<div class="floating-div">
  <p>i'll float!</p>
</div>

<div class="content-div">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto rerum aspernatur dolores, eos laborum illo, placeat minima, dolorum eaque perferendis ut nam eligendi quas quod minus deleniti dicta aut nemo.</p>
</div>

<div class="content-div">
  <p>I'm juust another content-div! Hey hey hey</p>
</div>