javascript 如何使用javascript更改元素的offsetHeight?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4925217/
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
how to change the offsetHeight of a element using javascript?
提问by harry
Hello i'm trying to change the offsetHeight of an element. i used the following
您好,我正在尝试更改元素的 offsetHeight。我使用了以下
document.getElementById('id').style.offsetHeight = 0;
but i saw no visible change. Can anyone help me please?
但我没有看到明显的变化。有人可以帮我吗?
回答by Saul
The offsetHeightproperty indicates the height of the visible area for an element. It's a shorthand that contains the sum of dimensions from padding, scrollbars and borders.
该offsetHeight属性指示元素的可见区域的高度。它是一种速记,包含填充、滚动条和边框的尺寸总和。
However, it can't be used to change the actual size and as noted in comments, offsetHeightis a property of an element, not style.
但是,它不能用于更改实际大小,并且如注释中所述,它offsetHeight是元素的属性,而不是样式。
To modify the actual size use height, paddingor border.
要修改实际大小,请使用height,padding或border。
回答by SLaks
You should set style.heightto a string ending in px.
您应该设置style.height为以px.
回答by Mohamed Allal
You should set style.heightand remember to add the unit at the end like 'px' , in the case you get it from offsetHeightfor example (well you know what unit you need). It's style and you have all the different units ('px','%','em', 'vh', ...etc).
Here is an example:
您应该设置style.height并记住在末尾添加单位,例如 'px' ,offsetHeight例如,如果您从中获得它(您知道您需要什么单位)。它的风格,你有所有不同的单位('px','%','em','vh',...等)。下面是一个例子:
myHeightInPx = 200;
DomElement.style.height = myHeightInPx + 'px';
Also to note is that offsetHeight return the height as a number, an integer. The unit is px. And if you get a value using it. you need always to add the unit 'px' when setting style.height, just like in above and the bellow example:
还要注意的是 offsetHeight 以数字形式返回高度,一个整数。单位是px。如果你使用它获得了价值。在设置 style.height 时,您需要始终添加单位“px”,就像上面和下面的示例一样:
DomElement.style.height = AnotherDOMelment.offsetHeight() + 'px';

