gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:39:15 25 4
gpt4 key购买 nike

我想将一个对象的高度用于另一个对象。如果对象 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() 函数在这种情况下有用吗?

最佳答案

让“阅读更多”按钮调用的函数测量元素的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>

关于javascript - 动态使用另一个元素的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31482415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com