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

后端 未结 4 933
攒了一身酷
攒了一身酷 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: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");
    

提交回复
热议问题