简体   繁体   中英

How to get margin left size using javascript when I use margin auto property in css

I have div with margin:auto; and I need get only margin-left size value using javascript :)

//css
.test{
        margin: auto;
        width: 100px;
        height: 100px;
        outline: 1px solid red;
    }


 // html
        <div class="test">Test</div>

Live example

Use this:

1) With jQuery

var left = $(".test").offset().left;

2) Or, second version is that: Replace your div to <div class="test" id="test"></div> , and use this js.

var left = document.getElementById("test").offsetLeft;

You don't need jQuery for that, plain JavaScript is enough:

var left, element = document.querySelector('.test');
if(element) {
  left = element.getBoundingClientRect().left;  
}

You can use window.getComputedStyle() method if you don't need IE8 support.

 var test = document.querySelector('.test');
 var left_margin = window.getComputedStyle(test).getPropertyValue("margin-left"); // returns margin e.g. '655px'
 left_margin = left_margin.match(/\d+/); //returns bare number e.g. '655'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM