javascript 我可以轻松“设置”元素的 offsetWidth 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4870469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:10:48  来源:igfitidea点击:

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

javascriptwidthdhtml

提问by Stephen

Note: I know offsetWidth is read only

注意:我知道 offsetWidth 是只读的

I'm trying to make a pop-up 'div' overlay a trelement with the exact same width.

我正在尝试使一个弹出式“div”覆盖tr具有完全相同宽度的元素。

However, I am stumped as to how to set my div's widthso that its offsetWidthis the exact same as the tr.

但是,我对如何设置我的div'swidth以使其offsetWidthtr.

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.

具体来说,如果可能的话,我想要 YUI 2 的答案。

采纳答案by Simon Lieschke

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

如果您将div's margin 和 paddings归零,则应该可以使用以下内容:

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

Depending on how you are dealing with borders on your divand tryou may want to assign tr.clientWidthinstead.

根据您处理边界的方式divtr您可能希望改为分配tr.clientWidth

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

然后,您可以根据需要在您的父/子元素上设置任何边距/填充div以获得所需的外观。

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

确定您想要做什么的关键是准确理解什么clientWidthoffsetWidth度量,并且width元素的 CSS是它的内容区域,不包括在其上定义的任何边距、边框和填充(请参阅此处的 W3C 框模型) .

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

您可以通过从

回答by JamesH

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 的宽度设置为已知值,然后找到该值与 div 的 offsetWidth 之间的差异。这应该告诉您将宽度设置为什么以使其适合。

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.

这真的很乱,但您不必以这种方式关心填充、边距或边框。