无法使用JavaScript调整DIV高度

时间:2017-09-12 06:38:23

标签: javascript jquery html css resize

我想用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

我不是不为什么?

2 个答案:

答案 0 :(得分:3)

Document#getElementsByName方法返回元素集合,因此您需要通过其索引获取第一个元素,否则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"
}); 

答案 1 :(得分:1)

如果您想使用 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" >