position() and tables
How can it be that this doesn't alert 0
(instead, it alerts 50
)?
I need the td position relative to the table
http://j开发者_StackOverflow中文版sfiddle.net/vxVCE/
HTML:
<div style="height:40px"></div>
<div>
<table id="tbl">
<tr>
<td id="td1">linje 1</td>
</tr>
<tr>
<td id="td2">linje 2</td>
</tr>
</table>
</div>
JS:
var elm = $('#td1');
var position = elm.position();
alert(position.top);
edit: I need the tr position relative to the table :)
Add position: relative;
to the table. Doing that will make it alert 0. Otherwise, it's finding position relative to the document.
Because it is not at the top -- therefore it is not zero
The body has a padding of 10px
.
The div above the table is 40px
in height.
Therefore it alerts "50
" (10 + 40 = 50
)
@Neal has explained beautifully why it gives 50. Here's the second part:
To get the position w.r.t the to table, subtract table's top from the td
top:
alert(position.top - $('#td1').closest('table').position().top);
Demo: http://jsfiddle.net/mrchief/vxVCE/1/
Note: Depending on your HTML/CSS, you might have to use table's offset
instead.
alert(position.top - $('#td1').closest('table').offset().top);
精彩评论