YUI - 获取真实的元素宽度?
我正在使用 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;
}
I am using YUI and need to get the true width of the element. The width of an element can be determined as follows.
width + border-left + border-right + padding-left + padding-right + margin-left + margin-right.
Below is what I have come up with. It appears to be working. I was just wondering if this is the best way to go about determining this or is there there a more efficient way?
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一个
offsetWidth
属性,它返回的正是您想要的想。There is an
offsetWidth
property that returns exactly what you want.