简体   繁体   中英

JS get the position of element based on the body when position absolute on element

I need to build a tooltip, but I need to position the tooltip based on the body because its position is absolute and I don't want any relative parent to break my style.

 <div style="position: relative;">
    <input>
    <p class="tooltip">tooltip</p>
 </div>

I need the tooltip to be on the input but always relative to the body.

How can I calc this?

Elements with position: absolute are always realtive to the first parent Element with relative . (or anything except static and fixed)

So to fix it you need to avoid using position: relative on the parent

<div>
   <input>
   <p class="tooltip">tooltip</p>
</div>

or since it's anyways absolute positioned move the tooltip out of the relative element.

<p class="tooltip">tooltip</p>
<div style="position: relative;">
   <input>
</div>

Using position:absolute; should position the tooltip relative to the nearest positioned element—in this case, the div marked position:relative; . (See the CSS3 reference on absolute positioning .)

So in your example, you don't need to worry about any parent elements with relative positioning, as they shouldn't affect the absolute positioning context. You should be able to simply use:

<div style="position: relative;">
  <input>
  <p class="tooltip" style="position:absolute; top:0; left:0;>tooltip</p>
</div>

Unless I'm misunderstanding your question, in which case, please provide more detailed examples.

EDIT:

If you're trying to avoid using position: relative , you can set the tooltip position with javascript:

var input = document.getElementById('input-id');
var tooltip = document.getElementById('tooltip-id');

tooltip.style.left = (input.offsetLeft)+'px';
tooltip.style.top = (input.offsetTop)+'px';

change class to style:

<div>
  <input>
  <p class="tooltip" style="position:relative;">tooltip</p>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM