javascript - 使用javascript根据元素高度和父高度更改元素填充
问题描述
我需要根据 h1 的高度和它的父级来更改 h1 的顶部填充的大小。填充顶部将是(h1 的高度 - h1 的父高度)/ 2
我仍然不明白为什么 JavaScript 代码不起作用。
window.onload = function() {
const h1 = document.getElementsByTagName("h1")[0];
h1.innerHTML = document.title;
h1.style.paddingTop = (((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString());
console.log(((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString());
}
header {
border-bottom: solid 1px black;
position: fixed;
height: 10vh;
width: 100%;
}
h1 {
margin: 0px;
margin-top: auto;
}
<header>
<h1>Text</h1>
</header>
解决方案
仅仅是因为您没有使用单位来识别评估填充的值。另外添加display: block
到h1
样式。查看这个JSBin演示。
window.onload = function() {
const h1 = document.getElementsByTagName("h1")[0];
h1.innerHTML = document.title;
h1.style.paddingTop = (((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString())+'vh'; // Use unit.
console.log(((h1.parentElement.clientHeight - h1.clientHeight) / 2).toString());
}
header {
border-bottom: solid 1px black;
position: fixed;
height: 10vh;
width: 100%;
}
h1 {
margin: 0px;
margin-top: auto;
display: block;
}
<header>
<h1>Text</h1>
</header>
推荐阅读
- c# - 返回多个 MemoryStream 作为 HttpResponseMessage
- spring-boot - NumberFormatException 与 couchdb apache camel 集成
- kotlin - Kotlin:如何在没有 runBlocking 的情况下等待非挂起的协程?
- javascript - 在 2 个数组之间传递时,值变得未定义
- rest - Apache Camel - 通过骆驼休息调用外部服务
- kotlin - 减少流量的操作需要挂起功能
- php - 从联系表 7 中的电话中删除 +
- hardware - 通过插入套接字的硬件设备访问 Internet
- node.js - 在 Node 中使用“fs”,我将如何流式传输 CSV 文件?
- reactjs - 使用 react-stripe-elements 将额外的值传递给条带 - 不起作用