2017-09-12 34 views
-1

div要素の高さをJavaScriptでリサイズします。このdiv要素から DIVの高さをJavaScriptでサイズ変更できません

が、私はこれは私のdiv要素がi'lサイズを変更したいです

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

高さを読んでいるこれは私はJavaScriptで

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

(これは複数にすることができます)コード:

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

はクロームでは、i'l次のエラーを取得します

Uncaught TypeError: Cannot set property 'height' of undefined 

どうしてですか?

答えて

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" 
}); 
+0

素晴らしいです。ありがとう。しかし、最初のdivだけがサイズ変更されます。他のものではありません.. – fcb1900

+0

@ fcb1900:更新 –

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" >

関連する問題