简体   繁体   中英

How do I get the CSS property top from a element in javascript

How 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 ?

尝试

element.style.top 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM