如何使用更少的代码计算元素的宽度和高度及其填充/边距值?

时间:2012-07-26 08:50:53

标签: jquery css height width

我正在使用height() / width()方法,但它的返回值没有它的填充和边距值。我没有问题用/高度值计算总数。

这种方式有效,但我的问题是;它太长了,无法计算所有这些。有没有办法用更少的代码计算这些没有错误?

Here is jsFiddle example.

jQuery的:

var ele = $('div');

var eleW = ele.width();
var eleH = ele.height();

alert(eleW);//returning 200
alert(eleH);//returning 100

var eleMR = parseInt(ele.css('margin-right'));
var eleML = parseInt(ele.css('margin-left'));
var eleMT = parseInt(ele.css('margin-top'));
var eleMB = parseInt(ele.css('margin-bottom'));

var elePR = parseInt(ele.css('padding-right'));
var elePL = parseInt(ele.css('padding-left'));
var elePT = parseInt(ele.css('padding-top'));
var elePB = parseInt(ele.css('padding-bottom'));

var eleTotalWidth = eleMR + eleML + elePR + elePL + eleW;
var eleTotalHeight = eleMT + eleMB + elePT + elePB + eleW;

alert(eleTotalWidth);//returning 147
alert(eleTotalHeight);//returning 122

的CSS:

div {
       float:left; width:100px; height:200px; background-color:#000;
       margin:5px 3px 2px 4px; padding:10px 20px 5px;
     }​

1 个答案:

答案 0 :(得分:11)

使用outerWidth();outerHeight();

var ele = $('div');

var eleW = ele.outerWidth(true);
var eleH = ele.outerHeight(true);