DIV 无法使用 JavaScript 调整高度

DIV height can't be resized with JavaScript

我想用 JavaScript 调整 div 元素的高度。

从这个div,我正在读取高度

<div class="pages" id="alles">

这是我的 div 我要调整大小(可以不止一个)

<div class="content-block" name="maxhoehe">

这是我的 JavaScript 代码:

var sh = document.getElementById("alles").offsetHeight;
         document.getElementsByName("maxhoehe").style.height = sh-180 + "px";

在 chrome 中,我收到以下错误:

Uncaught TypeError: Cannot set property 'height' of undefined

我不知道为什么?

Document#getElementsByName 方法 returns 元素集合,因此您需要通过其索引获取第一个元素,否则 style 属性 将是 undefined ( nodelist 没有任何样式 属性 )。

document.getElementsByName("maxhoehe")[0].style.height = (sh - 180) + "px";

要全部更新,遍历元素并更新 属性。

var elements = document.getElementsByName("maxhoehe");

// in latest browser use Array.from(elements)
[].slice.call(elements).forEach(function(ele){
   ele.style.height = (sh - 180) + "px"
}); 

如果你想使用 JQuery 使用下面的代码。

$('#change').on('click', function(){
  $('.content-block').height($('.pages').height());
});
div{
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pages" id="alles">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
<div class="content-block" name="maxhoehe">sad</div>
<input type="button" value="change" id="change" >