javascript - 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')
我可以访问一组更有限的属性。
解决方案
要获得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>
推荐阅读
- google-signin - Google OAuth 2.0 - 离线访问的增量授权
- javascript - google-maps-react 在拖动结束时获取标记位置
- python - Python Argparse 子解析器
- ruby-on-rails - 有没有办法知道迁移正在运行?
- python - numpy 随机生成器有偏差吗?
- python - 如何在python icrawler中使用搜索关键字重命名爬虫文件
- c# - WCF crm 连接失败,由于字符串不安全
- razor - 如何在 ASP.NET 网页中进行 MD5 散列(razor 语法/cshtml)
- python - 如何移动图片按钮?Pyqt5 蟒蛇
- git - Git,错误:远程解包失败:无法创建临时对象目录-通过创建新分支