![](/img/trans.png)
[英]How do I set the style.top property of an element in JavaScript?
[英]How do I get the CSS property top from a element in javascript
如何从javascript中的元素获取CSS属性顶部。
我已经尝试了document.getElementById(element).offsetTop
但是它总是返回0。当我设置了top时:500px; 在元素的CSS中。
offsetTop
获取元素在页面上的位置(相对于offsetParent,offsetParent是任何定位的元素,或者有时是某些其他类型的元素),以像素为单位。
style.top
在style="top: 500px"
内联属性中获取top
属性的String值。
如果要获取已从样式表中设置的top
样式值,则不能使用style.top
,它只会返回''
来告诉您top
尚未在style
属性中设置。 而是有window.getComputedStyle
(由DOM Level 2样式定义)和element.currentStyle
(由IE使用)定义。 (较早的浏览器也不支持。)
var top= (window.getComputedStyle?
window.getComputedStyle(element, null).getPropertyValue('top') :
element.currentStyle? element.currentStyle.top : '0'
);
通常有更好的方法可以避免尝试读取样式表。
offsetTop
将最高偏移量返回到树中position:relative;
较低节点position:relative;
或position:absolute;
组。
您将父母的位置设置为相对还是绝对 ?
尝试
element.style.top
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.