2017-10-11 51 views
1

我有2列並排。左欄包含我的控制之外的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

看到我的答案我想是這樣它就像你想@geejay –

回答

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); 
 
}
.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; 
 
}
<div> 
 
\t <div class="left"> 
 
    \t <div class="box1"> 
 
\t <p onclick="clicked(event)">Blah 1</p> 
 
     <p onclick="clicked(event)">Blah 2</p> 
 
    \t </div> 
 
    </div> 
 
<div class="right"> 
 
\t <div class="box2">Blah 1 stuff</div> 
 
    </div> 
 
</div>

0

top期望的長度值(top on MDN):

box2.style.top = top + "px"; 
0

既然你不使用jQuery標籤這個,這裏的香草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>