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

后端 未结 4 929
攒了一身酷
攒了一身酷 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 02:53

    Maybe you have to call your functions after document ready.

    If you use jQuery you can find left value faster:

     $(document).ready(function() {
         var $left = $('#my-div').css('left');
         console.log($left);
     });
    
    0 讨论(0)
  • 2021-01-04 03:07

    The problem is that, since CSS is loaded separately from the JS, there's no official way to ensure that the style.left property will be accurate. The style.left property is a different, higher-priority style override.

    You'll need to use the getComputedStyle function.

    https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle

    Ex:

    var div = document.getElementById('my-div');
    var style = getComputedStyle(div);
    var left = style.getPropertyValue("left");
    
    0 讨论(0)
  • 2021-01-04 03:13

    You should call this

    document.getElementById('my-div').style.left
    document.getElementById('my-div').offsetLeft
    

    when document is loaded, if you call it earlier it will return null because element doesnt exists yet. So you can use jQuery to determine when all content is loaded.

    $(function() {
        //put your code here
    });
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题