首页 > 解决方案 > Javascript 尝试始终将侧边栏保持在 100vh

问题描述

从事一个需要老式 CSS 支持的项目,并希望通过保持与元素框<aside>相同的高度来填充页面<article>(它可能位于页眉和页脚之间,在这种情况下它不会超出它们。)

<article id="article">
...
<aside id="sidebar">

这是我动态设置高度的尝试。它似乎不起作用。

<script>                                                                  
function sidebarHeight() {                                                
sidebar=window.document.getElementById('sidebar')                         
article=window.document.getElementById('article')                         
sidebar.style.height=article.style.height;                                
console.log('article.style.height: ' + article.style.height);             
}
window.onresize=sidebarHeight;                                            
</script>  

这不起作用,因为article.style.height始终具有值""而不是当前高度。如何保持侧边栏与文章高度同步垂直拉伸?

顺便说一句,有人可以解释为什么获得我知道有效的高度或至少颜色等属性的唯一方法需要调用getElementById()? 如果我使用听起来更合乎逻辑的方法,getElementsByTagName('article')我可以访问一组更有限的属性。

标签: javascriptdom

解决方案


要获得onresize您需要使用的计算高度.offsetHeight,您需要在返回值中添加一个单位。

sidebar.style.height = `${article.offsetHeight}px`; 

此外,您的 DOM 查询应该只被调用document

sidebar = document.getElementById('sidebar')                         
article = document.getElementById('article') 

article {
  float: left;
  height: 40vh;
  width: 75vw;
  background-color: gray;
}

aside {
  float: right;
  width: 20vw;
  background-color: tomato;
}
<article id="article"></article>
<aside id="sidebar"></aside>

<script>                                                                  
function sidebarHeight() {                                                
sidebar= document.getElementById('sidebar')                         
article= document.getElementById('article')                         
sidebar.style.height= `${article.offsetHeight}px`;         
}
window.onresize=sidebarHeight;                                            
</script>


推荐阅读