动态高度不起作用Javascript

时间:2018-05-04 10:30:49

标签: javascript html css

我试图通过计算标题div高度和页脚div高度动态地为div添加高度,但它不起作用,这是代码示例:

我期待处理纯javascript,没有JQuery

getSSIDList()
function contentHeight(e){
  var winH = document.documentElement.clientHeight;
  var headerH = document.getElementsByClassName('header')[0];
  var footerH = document.getElementsByClassName('footer')[0];
  var contentHei = winH - headerH.clientHeight - footerH.clientHeight;
  document.getElementsByClassName('content-inner')[0].clientHeight = contentHei + "px";
}
contentHeight();

1 个答案:

答案 0 :(得分:6)

您需要使用style.height才能使用JS

调整元素的高度

function contentHeight(e){
  var winH = document.documentElement.clientHeight;
  var headerH = document.getElementsByClassName('header')[0];
  var footerH = document.getElementsByClassName('footer')[0];
  var contentHei = winH - headerH.clientHeight - footerH.clientHeight;
  document.getElementsByClassName('content-inner')[0].style.height = contentHei + "px";
}
contentHeight();
body {
 margin:0;
}
<div class="header">
    this is content of header
</div>
<div class="content-inner">
    <!-- Apply dynamic height to this div by calculating header and footer height -->
</div>
<div class="footer">
    footer content
</div>

顺便说一下,我怀疑你希望你的内容占据屏幕的空闲左侧空间,你可以用纯CSS轻松完成。

这是flexbox的一个想法:

body {
 margin:0;
 height:100vh;
 display:flex;
 flex-direction:column
}

.content-inner {
  flex:1; /*Fill the empty space*/
  background:yellow;
}
<div class="header">
    this is content of header
</div>
<div class="content-inner">
    
</div>
<div class="footer">
    footer content
</div>