How do I get the CSS property top from a element in javascript
H开发者_开发百科ow do I get the CSS property top from a element in javascript.
I have tried document.getElementById(element).offsetTop
however this always returns 0. When I have set top: 500px; in the CSS of element.
offsetTop
gets the position of the element on the page (relative to an offsetParent, which is any positioned element or occasionally some other types of element) in pixels as a Number.
style.top
gets the String value of the top
property in style="top: 500px"
inline attributes only.
If you want to get a top
style value that has been set from a stylesheet, you can't use style.top
which will just return ''
to tell you top
hasn't been set in the style
attribute. Instead there is window.getComputedStyle
which is defined by DOM Level 2 Style, and element.currentStyle
which is used by IE. (Older browsers won't support either.)
var top= (window.getComputedStyle?
window.getComputedStyle(element, null).getPropertyValue('top') :
element.currentStyle? element.currentStyle.top : '0'
);
There are usually better ways around that don't involve trying to read stylesheets.
offsetTop
returns the top offset to the node lower in the tree that has position:relative;
or position:absolute;
set.
Do you have the parent's position set to relative or absolute?
Try
element.style.top
精彩评论