开发者问题收集

无法使用 JavaScript 调整 DIV 高度

2017-09-12
53

我想使用 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个回答

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

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"
}); 
Pranav C Balan
2017-09-12

如果您想使用 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" >
Shadow Fiend
2017-09-12