当我在 css 中使用边距自动属性时如何使用 javascript 获取边距左大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32564461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:28:17  来源:igfitidea点击:

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

javascriptjquery

提问by Val Do

I have divwith margin:auto;and I need get only margin-leftsize value using javascript :)

我有divmargin:auto;我只需要margin-left使用 javascript获取大小值:)

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


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

Live example

活生生的例子

采纳答案by Sherali Turdiyev

Use this:

用这个:

1) With jQuery

1) 使用 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.

2)或者,第二个版本是:将您的 div 替换为<div class="test" id="test"></div>,并使用此 js。

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

回答by gaelgillard

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

你不需要 jQuery,纯 JavaScript 就足够了:

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

回答by Lunokhod

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

如果不需要 IE8 支持,可以使用window.getComputedStyle()方法。

 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'