简体   繁体   English

如何使用javascript更改元素的offsetHeight?

[英]how to change the offsetHeight of a element using javascript?

Hello i'm trying to change the offsetHeight of an element. 您好我正在尝试更改元素的offsetHeight。 i used the following 我使用了以下内容

document.getElementById('id').style.offsetHeight = 0;

but i saw no visible change. 但我没有看到明显的变化。 Can anyone help me please? 有人可以帮我吗?

The offsetHeight property indicates the height of the visible area for an element. offsetHeight属性指示元素的可见区域的高度。 It's a shorthand that contains the sum of dimensions from padding, scrollbars and borders. 它是一个简写,包含填充,滚动条和边框的尺寸总和。

However, it can't be used to change the actual size and as noted in comments, offsetHeight is a property of an element, not style. 但是,它不能用于更改实际大小,并且如注释中所述, offsetHeight是元素的属性,而不是样式。

To modify the actual size use height , padding or border . 要修改实际大小,请使用heightpaddingborder

您应该将style.height设置为以px结尾的字符串。

You should set style.height and remember to add the unit at the end like 'px' , in the case you get it from offsetHeight for example (well you know what unit you need). 你应该设置style.height并记住在最后添加单位,如'px',例如你从offsetHeight获得它(你知道你需要什么单位)。 It's style and you have all the different units ('px','%','em', 'vh', ...etc). 这是风格,你有所有不同的单位('px','%','em','vh',...等)。 Here is an example: 这是一个例子:

myHeightInPx = 200;
DomElement.style.height = myHeightInPx + 'px';

Also to note is that offsetHeight return the height as a number, an integer. 另外要注意的是offsetHeight返回高度为数字,整数。 The unit is px. 单位是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: 在设置style.height时,您需要始终添加单位'px',就像上面和下面的示例一样:

DomElement.style.height = AnotherDOMelment.offsetHeight() + 'px';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM