无法为容器中的每个 div 设置属性高度(没有 jQuery!



我尝试在没有jQuery的情况下设置容器的高度。我想出了一个解决方案,只为第一个div 设置高度属性(甚至在 jsfiddle 中也无法做到这一点)。请帮忙。

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";
    }
galleryCol

元素。 在 for 循环中,您需要将y[i].style.height设置为 galleryCol 的高度,而不是元素本身。

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>

最新更新