动态地使用另一个元素的高度

use height of another element dynamically

本文关键字:元素 高度 另一个 动态      更新时间:2023-09-26

我想使用另一个对象的高度。如果对象1的高度改变(阅读更多按钮),对象2的高度也应该改变。我必须使用jQuery吗?

#vr {
  height: 0px;
  display: inline-block;
  background-color: #808080;
  border-style: solid;
  border-color: #808080;
  -webkit-transition: 1000ms ease in;
  -moz-transition: 1000ms ease-in;
  -o-transition: 1000ms ease-in;
  -ms-transition: 1000ms ease-in;
  transition: 1000ms ease-in;
  position: absolute;
  margin-top: -12px;
  margin-left: 12px;
  width: 1px;
  float:right;
  margin-left: 200px;
}
#content {
  width: 180px;
  font-family: 'Open Sans', sans-serif;
  text-align: justify;
  display: inline-block;
 
}
<script type="text/javascript">
  function bigger() {
    document.getElementById("vr").style.height = "100px";
  }
</script>
<body onload="bigger()">
  <div id="content">
    <p>test</p>
  </div>
  <hr id="vr" />
</body>

height()函数在这种情况下有用吗?

让"read more"按钮调用的函数测量元素的offsetHeight,然后设置第二个元素的高度。(为了简单起见,本例使用box-sizing: border-box,否则您必须考虑padding/border/margin的大小。)

function addListener() {
    var elem = document.getElementById("div1");
    if (elem) elem.addEventListener("click", showMore, false)
    else document.addEventListener("DOMContentLoaded", addListener, false);
}
addListener();
function showMore() {
    var elem = document.getElementById("div1");
    elem.style.maxHeight = "1000px";
    document.getElementById("div2").style.height = elem.offsetHeight + "px";
}
DIV {-webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;}
DIV {width: 100px; float: left; margin: 10px; border: 1px solid black; padding: 5px;}
#div1 {max-height: 100px; overflow: hidden;}
#div2 {height: 100px;}
<DIV ID="div1">click this container to extend its height, so that the whole text becomes visible.</DIV>
<DIV ID="div2"></DIV>