我有两列并排。左列包含我无法控制的HTML。右侧需要显示一个注释框,理想情况下该注释框与左侧单击的文本对齐。
如何相对于非兄弟姐妹绝对定位元素的顶部?
小提琴:https://jsfiddle.net/ark51cLu/4/
<div class="container">
<div class="left">
<div class="box1">
<div class="inner-html-box">
<p onclick="clicked(event)">Item 1</p>
<p onclick="clicked(event)">Item 2</p>
</div>
</div>
</div>
<div class="right">
<div id="comment-box" class="box2">Item 1 comments</div>
</div>
</div>
答案 0 :(得分:1)
你想这样,
将px
添加到最高值,例如
box2.style.top = top + "px";
function clicked(ev) {
var top = ev.target.getBoundingClientRect().top;
var box2 = document.querySelector('.box2');
box2.style.top = top + "px";
box2.innerText = ev.target.innerText;
console.log(top);
}
&#13;
.left{
float: left;
width:75%;
}
.right {
float: right;
width:25%;
}
.box1{
border: 1px solid red;
}
.box2{
border: 1px solid blue;
position: absolute;
top: 0;
right: 0;
}
&#13;
<div>
<div class="left">
<div class="box1">
<p onclick="clicked(event)">Blah 1</p>
<p onclick="clicked(event)">Blah 2</p>
</div>
</div>
<div class="right">
<div class="box2">Blah 1 stuff</div>
</div>
</div>
&#13;
答案 1 :(得分:0)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
需要一个长度值(top on MDN):
top
答案 2 :(得分:0)
由于你没有用jQuery标记这个,所以这是一个vanilla js版本。
const box1 = document.querySelector('.box1')
const box2 = document.querySelector('.box2')
box1.addEventListener('click', (e) => {
let top;
if(e.target.nodeName = "P") {
top = e.target.getBoundingClientRect().top
box2.style.transform = `translateY(${top}px)`
} else {
return
}
})
.left{
float: left;
width:75%;
}
.right {
float: right;
width:25%;
overflow: hidden
}
.box1{
border: 1px solid red;
}
.box2{
border: 1px solid blue;
position: absolute;
top: 0;
right: 0;
transition: transform .3s
}
<div>
<div class="left">
<div class="box1">
<p>Blah 1</p>
<p>Blah 2</p>
</div>
</div>
<div class="right">
<div class="box2">Blah 1 stuff</div>
</div>
</div>