我正在使用YUI,并需要获取元素的真实宽度。可以按照以下方式确定元素的宽度。
宽度 + 左边框宽度 + 右边框宽度 + 左内边距 + 右内边距 + 左外边距 + 右外边距。
以下是我想出的方法,它似乎有效。我只是想知道这是否是确定此内容的最佳方法,还是有更高效的方法?
YUI().use('node', function(Y) {
var node = Y.one('#nav');
var nodeWidth = trueElementWidth(node);
alert(nodeWidth);
});
function trueElementWidth(el) {
var width = 0;
var attributes = ['border-left', 'border-right', 'padding-left', 'padding-right', 'width', 'margin-right', 'margin-left'];
for(var i=0; i < attributes.length; i++) {
width = width + removePx(el.getComputedStyle(attributes[i]));
}
return width;
}
function removePx(el) {
el = el.toString();
length = el.length - 2;
elDimension = parseInt(el.substring(0, length));
return isNaN(elDimension) ? 0 : elDimension;
}