使用 jquery 获取元素的边距大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4219534/
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
get the margin size of an element with jquery
提问by laukok
How can I get the properties of an element with jquery? I want to get the size of the margin of a div in particular.
如何使用 jquery 获取元素的属性?我特别想获得 div 边距的大小。
I have set the style of the div in a .css file, for instance,
例如,我在 .css 文件中设置了 div 的样式,
.item-form {
margin:0px 0px 10px 0px;
background: blue;
}
the html,
html,
<form>
...
<div class="item-form">
<textarea class="autohide"></textarea>
</div>
...
</form>
I tried with this code, but it fails obviously,
我试过这段代码,但显然失败了,
$(".autohide").each(function(){
var $this = $(this);
alert($this.parents("div:.item-form").css("margin"));
});
any ideas? thanks.
有任何想法吗?谢谢。
回答by Orbling
The CSS tag 'margin' is actually a shorthand for the four separate margin values, top/left/bottom/right. Use css('marginTop')
, etc. - note they will have 'px' on the end if you have specified them that way.
CSS 标签“margin”实际上是四个独立边距值的简写,上/左/下/右。使用css('marginTop')
等 - 请注意,如果您以这种方式指定它们,它们将在末尾带有 'px'。
Use parseInt()
around the result to turn it in to the number value.
使用parseInt()
结果周围将其转换为数值。
NB. As noted by Omaty, the order of the shorthand 'margin' tag is:
top right bottom left
- the above list was not written in a way intended to be the list order, just a list of that specified in the tag.
注意。正如 Omaty 所指出的,速记“边距”标签的顺序是:
top right bottom left
- 上面的列表不是按照列表顺序的方式编写的,只是标签中指定的列表。
回答by Webnet
You'll want to use...
你会想用...
alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));
回答by Jordan
Exemple, for :
例如,对于:
<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>
In this js code :
在这个js代码中:
var myMarginTop = $("#myBlock").css("marginBottom");
The var becomes "15px", a string.
var 变成了“15px”,一个字符串。
If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.
如果你想要一个整数,为了避免 NaN(非数字),有多种方法。
The fastest is to use native js method :
最快的是使用原生js方法:
var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );
回答by Matthew J Morrison
From jQuery's website
Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.
不支持速记 CSS 属性(例如边距、背景、边框)。例如,如果要检索渲染的边距,请使用:$(elem).css('marginTop') 和 $(elem).css('marginRight'),依此类推。