How to calculate element's width and height wi

2019-02-10 10:49发布

问题:

I am using height() / width() method but its returning value without it's padding and margin values. I am not having problem to calculate total with / height values.

This way is working but my problem is; its too long to calculate all of them. Is there a way to calculate these with less code without bugs ?

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:

Use outerWidth(); and outerHeight();

var ele = $('div');

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