admin管理员组

文章数量:1241092

My question is fairly straightforward: How can you find the offsetTop of a child element pared to it's parent element (rather than the window top)?

The definition of offsetTop states that the property will return the value by which a child element is offset from the top of an offsetParent, but this doesn't seem to be the case in this JSFiddle: /.

My goal is to find the offset of the bolded orange text from the top of the scrollable div, not the window top. Is there any way to do this without calculating the heights of the above elements, paddings, margins, etc. and subtracting it from the offsetTop?

I'm looking for a JavaScript only solution. No jQuery please.

My question is fairly straightforward: How can you find the offsetTop of a child element pared to it's parent element (rather than the window top)?

The definition of offsetTop states that the property will return the value by which a child element is offset from the top of an offsetParent, but this doesn't seem to be the case in this JSFiddle: http://jsfiddle/h5KBK/.

My goal is to find the offset of the bolded orange text from the top of the scrollable div, not the window top. Is there any way to do this without calculating the heights of the above elements, paddings, margins, etc. and subtracting it from the offsetTop?

I'm looking for a JavaScript only solution. No jQuery please.

Share Improve this question edited Jul 7, 2013 at 3:58 Shrey Gupta asked Jan 1, 2013 at 3:45 Shrey GuptaShrey Gupta 5,6178 gold badges46 silver badges71 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 12

By definition offsetTop returns the top position of the object relative to the top side of its offsetParent element, in pixels.

Now offsetParent needs to be an element with a position other than static. If you change the position attribute of scroll element in your fiddle I get a value of 1012 as opposed to 1110 without the position attribute.

Actually, I did some more research and figured out the answer. The offsetParent must have a specified position:absolute or position:relative declaration, as shown in this JSFiddle: http://jsfiddle/h5KBK/1/

本文标签: javascriptHow to find offsetTop relative to parentnot window topStack Overflow