jQuery 如何获取元素的边距和填充?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7420434/
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-08-26 23:50:31  来源:igfitidea点击:

jQuery How to Get Element's Margin and Padding?

jquerypaddingmargin

提问by Tom

Just wondering - how using jQuery - I can get an elements formatted total padding and margin etc ? i.e. 30px 30px 30px 30px or 30px 5px 15px 30px etc

只是想知道 - 如何使用 jQuery - 我可以获得格式化的总填充和边距等元素?即 30px 30px 30px 30px 或 30px 5px 15px 30px 等

I tried

我试过

var margT = jQuery('img').css('margin');
var bordT = jQuery('img').css('border');
var paddT = jQuery('img').css('padding');

But this doesn't work ? http://jsfiddle.net/q7Mra/

但这行不通?http://jsfiddle.net/q7Mra/

回答by Dan Short

var bordT = $('img').outerWidth() - $('img').innerWidth();
var paddT = $('img').innerWidth() - $('img').width();
var margT = $('img').outerWidth(true) - $('img').outerWidth();

var formattedBord = bordT + 'px';
var formattedPadd = paddT + 'px';
var formattedMarg = margT + 'px';

Check the jQuery API docs for information on each:

检查 jQuery API 文档以获取有关每个的信息:

Here's the edited jsFiddleshowing the result.

这是显示结果的编辑过的jsFiddle

You can perform the same type of operations for the Height to get its margin, border, and padding.

您可以对 Height 执行相同类型的操作以获取其边距、边框和填充。

回答by Elias Zamaria

According to the jQuery documentation, shorthand CSS properties are not supported.

根据jQuery 文档,不支持速记 CSS 属性。

Depending on what you mean by "total padding", you may be able to do something like this:

根据“总填充”的含义,您可以执行以下操作:

var $img = $('img');
var paddT = $img.css('padding-top') + ' ' + $img.css('padding-right') + ' ' + $img.css('padding-bottom') + ' ' + $img.css('padding-left');

回答by RavenHursT

jQuery.css()returns sizes in pixels, even if the CSS itself specifies them in em, or as a percentage, or whatever. It appends the units ('px'), but you can nevertheless use parseInt()to convert them to integers (or parseFloat(), for where fractions of pixels make sense).

jQuery.css()以像素为单位返回大小,即使 CSS 本身以 em、百分比或其他形式指定它们。它附加单位('px'),但您仍然可以使用parseInt()将它们转换为整数(或者parseFloat(),对于像素的分数有意义的地方)。

http://jsfiddle.net/BXnXJ/

http://jsfiddle.net/BXnXJ/

    $(document).ready(function () {
    var $h1 = $('h1');
    console.log($h1);
    $h1.after($('<div>Padding-top: ' + parseInt($h1.css('padding-top')) + '</div>'));
    $h1.after($('<div>Margin-top: ' + parseInt($h1.css('margin-top')) + '</div>'));
});

回答by Brutus

This works for me:

这对我有用:

var tP = $("img").css("padding").split(" ");
var Padding = {
    Top: tP[0] != null ? parseInt(tP[0]) : 0,
    Right: tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0),
    Bottom: tP[2] != null ? parseInt(tP[2]) : (tP[0] != null ? parseInt(tP[0]) : 0),
    Left: tP[3] != null ? parseInt(tP[3]) : (tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0))
};

Result example:

结果示例:

Object {Top: 5, Right: 8, Bottom: 5, Left: 8}

To make a total:

合计:

var TotalPadding = Padding.Top + Padding.Right + Padding.Bottom + Padding.Left;

回答by Andreas

I've a snippet that shows, how to get the spacings of elements with jQuery:

我有一个片段,显示了如何使用 jQuery 获取元素的间距:

/* messing vertical spaces of block level elements with jQuery in pixels */

console.clear();

var jObj = $('selector');

for(var i = 0, l = jObj.length; i < l; i++) {
  //jObj.eq(i).css('display', 'block');
  console.log('jQuery object:', jObj.eq(i));
  console.log('plain element:', jObj[i]);

  console.log('without spacings                - jObj.eq(i).height():         ', jObj.eq(i).height());
  console.log('with padding                    - jObj[i].clientHeight:        ', jObj[i].clientHeight);
  console.log('with padding and border         - jObj.eq(i).outerHeight():    ', jObj.eq(i).outerHeight());
  console.log('with padding, border and margin - jObj.eq(i).outerHeight(true):', jObj.eq(i).outerHeight(true));
  console.log('total vertical spacing:                                        ', jObj.eq(i).outerHeight(true) - jObj.eq(i).height());
}

回答by simshaun

Border

边界

I believe you can get the border width using .css('border-left-width'). You can also fetch top, right, and bottom and compare them to find the max value. The key here is that you have to specify a specific side.

我相信您可以使用.css('border-left-width'). 您还可以获取顶部、右侧和底部并比较它们以找到最大值。这里的关键是您必须指定特定的一面。

Padding

填充

See jQuery calculate padding-top as integer in px

参见jQuery 将 padding-top 计算为 px 中的整数

Margin

利润

Use the same logic as border or padding.

使用与边框或填充相同的逻辑。

Alternatively, you could use outerWidth. The pseudo-code should be
margin = (outerWidth(true) - outerWidth(false)) / 2. Note that this only works for finding the margin horizontally. To find the margin vertically, you would need to use outerHeight.

或者,您可以使用outerWidth。伪代码应该是
margin = (outerWidth(true) - outerWidth(false)) / 2. 请注意,这仅适用于水平查找边距。要垂直查找边距,您需要使用externalHeight

回答by José P. Airosa

If the element you're analyzing does not have any margin, border or whatsoever defined you won't be able to return it. At tops you'll be able to get 'auto' which is normally the default.

如果您正在分析的元素没有任何边距、边框或任何定义,您将无法返回它。在顶部,您将能够获得“自动”,这通常是默认设置。

From your example I can see that you have margTas variable. Not sure if're trying to get margin-top. If that's the case you should be using .css('margin-top').

从您的示例中,我可以看到您具有margT变量。不确定是否试图获得利润率最高。如果是这种情况,您应该使用.css('margin-top').

You're also trying to get the stylization from 'img' which will result (if you have more than one) in an array.

您还试图从 'img' 获取样式,这将导致(如果您有多个)数组。

What you should do is use the .each()jquery method.

你应该做的是使用.each()jquery 方法。

For example:

例如:

jQuery('img').each(function() {
    // get margin top
    var margT = jQuery(this).css('margin-top');

    // Do something with margT
});

回答by WantToDo

$('img').margin() or $('img').padding()

return:

返回:

{bottom: 10 ,left: 4 ,top: 0 ,right: 5}

get value:

获取价值:

$('img').margin().top

Edit:

编辑:

use jquery plugin: jquery.sizes.js

使用 jquery 插件:jquery.sizes.js