【问题标题】:YUI - Get True element width?YUI - 获得真正的元素宽度?
【发布时间】:2011-05-07 09:39:09
【问题描述】:

我正在使用 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;
}

【问题讨论】:

  • 快速回答:去 quirksmode.org,他们在那里解决了跨浏览器问题

标签: yui width


【解决方案1】:

有一个 offsetWidth 属性可以准确返回您想要的内容。

【讨论】:

  • offsetWidth 不包括边距值。
  • 边距不是元素的一部分,是吗?
  • 不,不是。我猜offsetWidth(仅包括填充+边框)并不完全符合 OP 的规范,但它满足了他的需求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-10
  • 1970-01-01
  • 2018-01-12
  • 2021-05-09
相关资源
最近更新 更多