gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:36:23 25 4
gpt4 key购买 nike

我希望我的 div(默认情况下 style="display: none; position: absolute",它仅在单击单元格时可见)显示在 30px 中从表格中单击的单元格左侧。 addevent 代表我想要将 30px 放在单元格左侧的 div。所以,我希望我的 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>

关于Javascript/根据另一个元素的位置定位一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28107757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com