如何使用JavaScript获取div的CSS left-property值 [英] How to get the CSS left-property value of a div using JavaScript
问题描述
我的CSS规则如下所示:
My CSS rule looks like this:
#my-div{
display: none;
position: absolute;
left: -160px;
bottom: -150px;
}
我正试图获得左边属性的值,如下所示:
I'm trying to get value of the left-property like this:
-
document.getElementById('my-div')。style.left
-
document.getElementById('my-div')。offsetLeft
document.getElementById('my-div').style.left
document.getElementById('my-div').offsetLeft
问题是两者都返回 null
。问题出在哪里?
The problem is that both return null
. Where is the problem?
推荐答案
问题是 someElement.style.left
只有内联样式才有效。由于您通过样式表应用样式,因此无法按预期方式获取值。
The problem is that someElement.style.left
only work if you have inline style. Since you apply your styling through a stylesheet, you will not be able to fetch the value the way you expect.
您可以采取其他几种方法来获取通过JavaScript的价值:
You have a couple of other approaches you could take to get the value through JavaScript:
window.getComputedStyle:
有可能使用 window.getComputedStyle获取元素的计算样式
,问题是它的支持非常有限(IE9 +)。如果您仍然想要使用它,您可以将其包装在一个函数中,以使每个属性更容易:
It is possible to get the computed style of an element using window.getComputedStyle
, the problem is that it has quite limited support (IE9+). If you still want to use it you could wrap it up in a function to make it a bit easier to get each property:
function getCssProperty(elmId, property){
var elem = document.getElementById(elmId);
return window.getComputedStyle(elem,null).getPropertyValue(property);
}
// You could now get your value like
var left = getCssProperty("my-div", "left");
Working example
jQuery(或其他一些库):
另一种选择是使用像 jQuery (或任何你喜欢的)的JavaScript库,它将为您提供跨浏览器解决方案以获取价值。
Another option would be to use a JavaScript library like jQuery (or whatever you prefer), which will provide you with a cross-browser solution to get the value.
使用jQuery,您可以使用 .css()
方法读取元素的CSS属性。
With jQuery you could use the .css()
method to read the CSS-property of the element.
$(function () {
var left = $("#my-div").css("left");
});
Working example
这篇关于如何使用JavaScript获取div的CSS left-property值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!