开发者

Can I easily "set" an element's offsetWidth?

Note: I know offsetWidth is read only

I'm trying to make a pop-up 'div' overlay a tr element 开发者_StackOverflow社区with the exact same width.

However, I am stumped as to how to set my div's width so that its offsetWidth is the exact same as the tr.

The calculation would look something like:

div.width = tr.offsetWidth - div.paddingWidth - div.marginWidth

but surely there's a better way (since I can only think of getting the padding and margin offsets in groups of two...)

Specifically, I'd like an answer for YUI 2 if possible.


If you zero out your div's margin and paddings then something like the following should work:

YAHOO.util.Dom.setStyle(div, 'width', tr.offsetWidth + 'px');

Depending on how you are dealing with borders on your div and tr you may want to assign tr.clientWidth instead.

You can then set any margin/paddings as required on the parent/child elements of your div to achieve the desired appearance.

The key to working out what you'll want to do is understanding exactly what clientWidth and offsetWidth measure, and that the CSS width of an element is its content area and excludes any margin, border, and padding defined on it (see the W3C box model here).

You could include the padding etc. in your calculation by querying it from the


It's a little messy and I may get downvoted for suggesting it, but one way you could do this without messing with your margin or padding is to set the div's width to a known value, then finding the difference between that and the div's offsetWidth. That should tell you what to set the width to in order to make it fit.

div.style.width = '20px'
diff = div.offsetWidth - 20;
div.style.width = tr.offsetWidth - diff;

It is really messy but you don't have to care about the padding, margin or border this way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜