javascript - HTML/Javascript-为什么我不能对表格内的 div 使用 offsetTop?

标签 javascript html

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;
}

jsFiddle example

关于javascript - HTML/Javascript-为什么我不能对表格内的 div 使用 offsetTop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20503302/

相关文章:

javascript - React - 在其自己的声明中获取组件的属性以在另一个属性中使用其值?

javascript - 检测微信二维码是否被扫描

javascript - jquery mouseup 无法正常工作

css - 设置元素的宽度

html - 溢出-x : auto on iPhone is not scrolling

html - 用CSS生成箭头线

javascript - jQuery document.on() 子选择器

javascript - 将 AJAX 响应的第一个元素设置为下拉列表中的选定值

javascript - 如何使 Javascript 正则表达式仅在两个字符彼此相邻时匹配?

javascript - 使用 Canvas 选择 pdf 文档的一部分