遍历每个元素并记录高度

时间:2019-05-10 09:52:04

标签: javascript

我希望能够记录每个.slide-text-overlay元素的高度,但是似乎没有显示任何值。简单的for循环应该遍历每个类,只记录该类的html,然后记录高度-但高度不记录;而是在控制台中只空一行。

有什么想法我在这里做错了吗?感谢您的帮助

var overlays = document.querySelectorAll('.overlay');
for (let overlay of overlays) {
  console.log(overlay);
  console.log(overlay.style.height);
}
.overlay:first-of-type {
color: red;
width: 100px;
height: 50px;
background: orange;
}
.overlay:nth-of-type(2) {
color: blue;
width: 100px;
height: 75px;
background: pink;
}
<div class='overlay'>
overlay 1
</div>
<div class='overlay'>
overlay 2
</div>

3 个答案:

答案 0 :(得分:2)

在JS中使用偏移高度

var overlays = document.querySelectorAll('.overlay');
for (var i=0; i < overlays.length; i++) {
  console.log(overlays[i].offsetHeight)
}
.overlay:first-of-type {
  color: red;
  width: 100px;
  height: 50px;
  background: orange;
}
.overlay:nth-of-type(2) {
  color: blue;
  width: 100px;
  height: 75px;
  background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='overlay'>
  overlay 1
</div>
<div class='overlay'>
  overlay 2
</div>

  

文档:   https://www.w3schools.com/jsref/prop_element_offsetheight.asp

答案 1 :(得分:1)

querySelector中的类应该是重叠的

var overlays = document.querySelectorAll('.overlay');
for (let overlay of overlays) {
  console.log(overlay);
  console.log(overlay.style.height);
}
.overlay:first-of-type {
color: red;
width: 100px;
height: 50px;
background: orange;
}
.overlay:nth-of-type(2) {
color: blue;
width: 100px;
height: 75px;
background: pink;
}
<div class='overlay'>
overlay 1
</div>
<div class='overlay'>
overlay 2
</div>

答案 2 :(得分:0)

尝试一下:

var overlays = document.getElementsByClass('.overlay');
for (let overlay of overlays) {
  console.log(overlay);
  console.log(overlay.style.height);
}