使用scrollHeight绘制div



我需要画一个高度为整个文档的div。一个名为";背景";应具有与内容相等的高度。我正试图通过获取scrollHeight来获得结果。我已经从下面的代码中知道了高度,但我不知道如何将值放入css中。提前感谢您的帮助!

document.getElementById("background").text = ("scrollHeight : " + $(".demo").prop("scrollHeight"));
.content {
background: #eee;
width: 100%;
height: 2000px;
}
#background {
width: 200px;
background: #000;
position: absolute;
top: 0;
left: 0;
height: 100%;
}
<div id="background"></div>
<div class="content"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

一种方法是使用getComputedStyle

document.querySelector('#background').setAttribute('style','height:'+ window.getComputedStyle(document.querySelector('.content')).getPropertyValue('height'));
.content {
background: #eee;
width: 100%;
height: 2000px;
}
#background {
width: 200px;
background: #000;
position: absolute;
top: 0;
left: 0;
/*height: 200px;*/
}
<div id="background"></div>
<div class="content"></div>

要在每次更改内容height时使背景具有相同的高度,它必须是内容的子级。

对于背景,将高度设置为inherit

.content {
background: #eee;
width: 100%;
height: 2000px;
}
#background {
width: 200px;
background: #000;
position: absolute;
top: 0;
left: 0;
height: inherit;
}
<div class="content">
<div id="background"></div>
</div>

希望我能帮助你。

document.getElementById("background").style.height = <get .content height>

https://www.w3schools.com/jsref/prop_style_height.asp

最新更新