如何使用JavaScript获取div的CSS left属性值? [英] How to get the CSS left-property value of a div using JavaScript?
问题描述
我的CSS规则如下:
#my-div {
display:none;
position:absolute;
left:-160px;
bottom:-150px;
}
我试图获得left属性的值如下: / p>
-
document.getElementById('my-div')。style.left
li>
-
document.getElementById('my-div')。offsetLeft
问题是两个返回 null
。问题在哪里?
问题是 someElement.style.left
仅当你有内联样式时才工作。由于您通过样式表应用样式,您将无法按照预期的方式获取值。
您可以使用其他几种方法通过JavaScript的值:
window.getComputedStyle:
使用 window.getComputedStyle $ c $获取元素的计算样式c>
,问题是它有相当有限的支持(IE9 +)。如果你仍然想要使用它,你可以将它包装在一个函数,使它有点更容易得到每个属性:
function getCssProperty(elmId,property){
var elem = document.getElementById(elmId);
return window.getComputedStyle(elem,null).getPropertyValue(property);
}
//你现在可以得到你的值如
var left = getCssProperty(my-div,left);
$ b
b 另一个选择是使用像 jQuery (或任何您喜欢的)这样的JavaScript库,它将为您提供跨浏览器解决方案 使用jQuery,您可以使用 My CSS-rule look like this: I'm trying to get value of the left-property like this: The problem is that both return The problem is that You have a couple of other approaches you could take to get the value through JavaScript: window.getComputedStyle: It is possible to get the computed style of an element using jQuery (or some other library): 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. With jQuery you could use the 这篇关于如何使用JavaScript获取div的CSS left属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
.css()
方法读取元素的CSS属性。
$(function(){
var left = $(#my-div)。css(left);
}
#my-div{
display: none;
position: absolute;
left: -160px;
bottom: -150px;
}
document.getElementById('my-div').style.left
document.getElementById('my-div').offsetLeft
null
. Where is the problem?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.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");
.css()
method to read the CSS-property of the element.$(function () {
var left = $("#my-div").css("left");
});