offsetTop 属性应该返回对象的绝对位置。当我使用表外的对象时效果很好,但如果对象在表内,它总是返回 1。为什么会发生这种情况以及如何避免这种情况?
查看问题示例: http://jsfiddle.net/6Y7qp/
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<div id='a' >a
<table style='border:solid thin black'>
<tr>
<td>
<div id='b'>b in table</div>
</td>
</tr>
</table>
<button onclick="document.getElementById('p').innerHTML='offsetTop:\na='+document.getElementById('a').offsetTop+'\nb='+document.getElementById('b').offsetTop">Show Off Set Top</button>
</div>
<pre id='p'>
</pre>
在此示例中,我需要获取“a”和“b”offsetTop,但在我的 firefox 和 chrome 浏览器中它总是为“b”返回 1
最佳答案
因为这就是它应该工作的方式。正如 MDN 所述:
offsetTop returns the distance of the current element relative to the top of the offsetParent node.
你说的offsetParent是什么?很高兴你问:
offsetParent returns a reference to the object which is the closest (nearest in the containment hierarchy) positioned containing element. If the element is non-positioned, the nearest table cell or root element (html in standards compliant mode; body in quirks rendering mode) is the offsetParent.
解决此问题的一种方法是通过以下方式在表格单元格中的 div 上设置一个位置:
td div {
position:relative;
}
关于javascript - HTML/Javascript-为什么我不能对表格内的 div 使用 offsetTop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20503302/