如何使用JavaScript获取div的CSS left属性值? [英] How to get the CSS left-property value of a div using JavaScript?

查看:179
本文介绍了如何使用JavaScript获取div的CSS left属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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 ,问题是它有相当有限的支持(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,您可以使用 .css() 方法读取元素的CSS属性。

  $(function(){
var left = $(#my-div)。css(left);
}

工作示例


My CSS-rule look 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

The problem is that both return null. Where is the problem?

解决方案

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.

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 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 (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 .css() method to read the CSS-property of the element.

$(function () {
  var left = $("#my-div").css("left");
});

Working example

这篇关于如何使用JavaScript获取div的CSS left属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆