动态使用另一个元素的高度 [英] use height of another element dynamically

查看:77
本文介绍了动态使用另一个元素的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个物体的高度用于另一个物体.如果对象1的高度发生变化(阅读更多按钮),则对象2的高度也应发生变化.我必须为此使用jQuery吗?

I want to use the height of an object for another one. If the height of object 1 changes (read more button), the height of object 2 should change as well. Do I have to use jQuery for this?

#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()函数在这种情况下有用吗?

Is the height() function useful in this context?

推荐答案

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

Make the function that is called by the "read more" button measure the element's offsetHeight, and then set the height of the second element. (The example uses box-sizing: border-box for simplicity, otherwise you have to take padding/border/margin sizes into account.)

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>

这篇关于动态使用另一个元素的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆