How to get the CSS left-property value of a div using JavaScript

后端 未结 4 927
攒了一身酷
攒了一身酷 2021-01-04 02:19

My CSS rule looks like this:

#my-div{
    display: none;
    position: absolute;
    left: -160px;
    bottom: -150px         


        
4条回答
  •  时光说笑
    2021-01-04 03:18

    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

提交回复
热议问题