首页 > 解决方案 > 使用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>

标签: javascripthtmlcss

解决方案


仅仅是因为您没有使用单位来识别评估填充的值。另外添加display: blockh1样式。查看这个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>


推荐阅读