javascript - 如果有 3 个或更多元素,则可滚动的 div

标签 javascript html

我有一个 block ,其用户地址 (div) 的数量可以是零或一个或更多。我希望如果 div 的数量是 3 或更多,那么 block 是可滚动的并且 block 的最大高度等于3个地址的高度(3格) 或者(最大高度myDIV=地址-详情1的高度+地址-详情2的高度+地址-详情3的高度)

.但我不知道哪里出了问题?

https://jsfiddle.net/tp8hc72k/3/

var nodelist = document.getElementsByClassName("address-details").length;
if (nodelist >= 3) {
  maxhght = 0
  for (i = 0; i < 3; i++) {
    var elmnt = document.getElementById('myDIV').children[i];
    maxhght += elmnt.offsetHeight;
  }

  //alert(maxhght);
  document.getElementById("myDIV").setAttribute(
    "style", "maxHeight:maxhght;overflow: auto;width:100%");
}
.address-details {
  border: 1px solid black;
  margin: 0.5rem
}

#myDIV {
  border: 2px solid red;
}
<div id="myDIV">
  <div class="address-details">The 1 address element in the document.</div>
  <div class="address-details">The 2 address element in the document.</div>
  <div class="address-details">The 3 address element in the document.</div>
  <div class="address-details">The 3 address element in the document.</div>
  <div class="address-details">The 3 address element in the document.</div>
  <div class="address-details">The 3 address element in the document.</div>
</div>

<button onclick="myFunction()">Try it</button>

最佳答案

用这一行替换最后一行:

document.getElementById("myDIV").setAttribute(
"style", "max-height:"+maxhght+"px;overflow: auto;width:100%");

关于javascript - 如果有 3 个或更多元素,则可滚动的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57803311/

相关文章:

javascript - 我可以使用 Google Chrome 扩展程序阻止alert()吗

javascript - 在 javascript case 语句中,当存在 if else 时,我应该放置多个中断还是仅一个中断?

php - 尝试使用 PHP 在 <select> 元素中选择一个选项

javascript - 添加上一个下一个导航到列表项淡入/淡出循环

javascript - JavaScript中对象的多级嵌套

php - UPDATE 反射(reflect)在 DB 但不是 SELECT 查询

html - 如何转换HTML标签中的转义字符?

javascript - 获取下拉列表中选定的值并将其放入其他下拉列表中?

html - 手机问题: transform: scale() resizes image when clicked

javascript - 调用方法比从内存中检索内容更快