获得表格中的元素偏移量 [英] Getting offsetTop of element in a table
问题描述
我似乎无法弄清楚如何获得表格中元素的偏移量。它适用于表格外的元素,但表格中的所有元素都返回相同的结果,并且通常位于页面的顶部。我在Firefox和Chrome中尝试了这一点。如何获得表中元素的offsetTop?
offsetTop
返回一个相对于 offsetParent
的值;您需要通过所有父母递归添加 offsetParent.offsetTop
,直到 offsetParent
为 null
。考虑使用 jQuery 的 offset
()
方法。
编辑:如果你不想使用jQuery,你可以编写一个像这样的方法(未经测试):
函数偏移量(elem){
if(!elem)elem = this;
var x = elem.offsetLeft;
var y = elem.offsetTop;
while(elem = elem.offsetParent){
x + = elem.offsetLeft;
y + = elem.offsetTop;
}
return {left:x,top:y};
}
I can't seem to figure out how to get the offsetTop of an element within a table. It works fine on elements outside tables, but all of the elements within a table return the same result, and it's usually at the top of the page. I tried this in Firefox and Chrome. How do I get the offsetTop of an element in a table?
offsetTop
returns a value relative to offsetParent
; you need to recursively add offsetParent.offsetTop
through all of the parents until offsetParent
is null
. Consider using jQuery's offset
()
method.
EDIT: If you don't want to use jQuery, you can write a method like this (untested):
function offset(elem) {
if(!elem) elem = this;
var x = elem.offsetLeft;
var y = elem.offsetTop;
while (elem = elem.offsetParent) {
x += elem.offsetLeft;
y += elem.offsetTop;
}
return { left: x, top: y };
}
这篇关于获得表格中的元素偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!