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

时间:2015-07-17 18:29:14

标签: javascript jquery html css

我想将对象的高度用于另一个对象。如果对象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()函数在此上下文中是否有用?

1 个答案:

答案 0 :(得分:1)

制作由&#34调用的函数;阅读更多&#34;按钮测量元素的offsetHeight,然后设置第二个元素的高度。 (为简单起见,该示例使用box-sizing: border-box,否则您必须考虑填充/边框/边距大小。)

&#13;
&#13;
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";
}
&#13;
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;}
&#13;
<DIV ID="div1">click this container to extend its height, so that the whole text becomes visible.</DIV>
<DIV ID="div2"></DIV>
&#13;
&#13;
&#13;