2017-05-03 40 views
-3

根据MDNabsolute定位元素被定位为“相对于其最接近定位的祖先”。如何确定一个元素是否“定位”?

我知道如何遍历DOM树,但是如何确定一个元素是否被视为“定位”?

+0

什么是你希望这个做什么?我可以根据具体情况考虑一些可行的事情,但不是一个通用的解决方案。 –

+0

您是否正在寻找一种以编程方式执行此操作的方式? – j08691

+0

@ j08691是...以编程方式。在JavaScript中。 – mpen

回答

1

参见the specification

一个元素表示,如果它的“位置”属性具有比“静态”以外的值,以进行定位。

+0

真的吗?我认为只是“相对”和“绝对”的定位。 '固定'和'粘'也是?感谢官方的参考 – mpen

0

这里有一个如何得到一个元素的绝对位置的小例子:

let target = document.getElementById('e'); 
 

 

 
let p = target; 
 
let pos; 
 
do { 
 
    p = p.parentElement; 
 
    pos = window.getComputedStyle(p).getPropertyValue("position"); 
 
} while (p.parentElement && pos === 'static'); 
 

 

 

 
let rect = target.getBoundingClientRect(); 
 
let offset = p.getBoundingClientRect(); 
 

 

 

 
let output = document.getElementById('o'); 
 

 
let x = rect.left - offset.left; 
 
let y = rect.top - offset.top; 
 

 
output.innerText = `Rect: ${rect.left}, ${rect.top} 
 
Offset: ${offset.left}, ${offset.top} 
 
Fixed: ${x}, ${y} 
 
`; 
 

 
let overlay = document.getElementById('overlay'); 
 

 

 

 
Object.assign(overlay.style, { 
 
    left: `${x}px`, 
 
    top: `${y + rect.height}px`, 
 
})
#a { 
 
    border: 1px solid red; 
 
    padding: 5px 10px 2px 8px; 
 
} 
 

 
#b { 
 
    border: 1px solid blue; 
 
    padding: 2px 7px 5px 6px; 
 
    position: relative; 
 
} 
 

 
#c { 
 
    border: 1px solid green; 
 
    padding: 9px 10px 4px 8px; 
 
} 
 

 
#d { 
 
    border: 1px solid orange; 
 
    padding: 1px 6px 9px 18px; 
 
} 
 

 
#e { 
 
    border: 1px solid cyan; 
 
    padding: 4px 12px 2px 3px; 
 
} 
 

 
output { 
 
    font-family: monospace; 
 
    white-space: pre; 
 
    margin-top: 10px; 
 
} 
 

 
#overlay { 
 
    background-color: rgba(255, 255, 0, .8); 
 
    position: absolute; 
 
    width: 200px; 
 
}
<div id="a"> 
 
    <div id="b"> 
 
    <div id="c"> 
 
     <div id="d"> 
 
     <div id="e"> 
 
      Hello 
 
      <div id="overlay">Positioned directly under cyan box</div> 
 
     </div> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div> 
 
</div> 
 

 

 

 
<output id="o">

相关问题