2017-10-12 36 views
0

我嘗試設置沒有jQuery的容器的高度。我想出了一個解決方案,只設置第一個div的高度屬性(甚至不能在jsfiddle中完成)。請幫忙。無法爲容器中的每個div設置屬性高度(沒有jQuery!)

https://jsfiddle.net/olivetum/x59hetL5/1/

<div class="gallery"> 
<div id="setWidth" class="gallery-col box shadow">Lorem</div> 
<div class="gallery-col box shadow">Lorem</div> 
<div class="gallery-col box shadow">Lorem</div> 
<div class="gallery-col box shadow">Lorem</div> 
</div> 
.gallery { 
    display: flex; 
    flex-wrap: wrap; 
} 
.gallery-col { 
    width: calc(50% - 2px); 
} 
.box { 
    background: orange; 
    margin: 1px; 
    border-radius: 3px; 
    } 
// SET GALLERY COLUMN WIDTH 
    var galleryCol = document.getElementById("setWidth"); 
    var y = document.getElementsByClassName("gallery-col"); 
    var i; 
    for (i = 0; i < y.length; i++) { 
     y[i].style.height = galleryCol + "px"; 
    } 

回答

0

galleryCol指DOM元素而不是高度。爲了得到它的計算高度,使用window.getComputedStyle()訪問DOM節點的高度,而不是,即:

var galleryColHeight = window.getComputedStyle(galleryCol).height; 

見下驗證的概念,在這裏我特意增加了#setWidth元素的高度,以證明其他高度基於其計算高度:

// Get DOM node and its computed height 
 
var galleryCol = document.getElementById("setWidth"); 
 
var galleryColHeight = window.getComputedStyle(galleryCol).height; 
 

 
// Iterate through DOM node collection 
 
var y = document.getElementsByClassName("gallery-col"); 
 
for (var i = 0; i < y.length; i++) { 
 
    y[i].style.height = galleryColHeight; 
 
}
.gallery { 
 
    display: flex; 
 
    flex-wrap: wrap; 
 
} 
 

 
.gallery-col { 
 
    width: calc(50% - 2px); 
 
} 
 

 
.box { 
 
    background: orange; 
 
    margin: 1px; 
 
    border-radius: 3px; 
 
}
<div class="gallery"> 
 
    <div id="setWidth" class="gallery-col box shadow">Lorem<br/>ipsum<br/>dolor<br/>sit<br/>amet</div> 
 
    <div class="gallery-col box shadow">Lorem</div> 
 
    <div class="gallery-col box shadow">Lorem</div> 
 
    <div class="gallery-col box shadow">Lorem</div> 
 
</div>

+0

謝謝你的回答。現在我發現我忘了在我的第一個js行中添加'offsetWidth'。現在一切正常。 ;) – user8103342

1

galleryCol是元素。在for循環中,您需要將y[i].style.height設置爲galleryCol的高度,而不是元素本身。

相關問題