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

时间:2015-01-23 10:25:52

标签: javascript html-table

我想要我的div(默认情况下为style="display: none; position: absolute",只有在单击一个单元格时才可见)才能显示在表格中单击的单元格左侧的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;
};

1 个答案:

答案 0 :(得分:1)

正如我在评论中所说,这可能是一个统一的错误。参见示例:

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>