首页 > 解决方案 > 如何使用javascript将具有给定类的每个元素的字体缩放到其父尺寸?

问题描述

我正在尝试制作我的第一个响应式网站,但遇到了一些问题。

特别是,我需要一些文本居中,但是当我在 FireFox 开发版中使用响应式设计模式尝试不同的窗口大小时,居中的文本不会真正适合其容器。所以,我认为 JavaScript 可能是最好的做法。

虽然这适用于使用 选择的元素document.getElementById('id');,但我似乎无法通过使用for循环使其与类一起使用。

这是我用于具有 ID 的元素的代码:

document.getElementById('header-text').style.fontSize = ((19/47.73) * document.getElementById('header-title').getBoundingClientRect().height).toString().concat('px');

这是我尝试使用通用类的元素。

var allIconLinks = document.getElementsByClassName('extras-iconlink-text');
var i;
for ( i = 0; i > allIconLinks.length; i++ ) {
    allIconLinks[i].style.fontSize = (19.2/42.43) * allIconLinks[i].parentElement.getBoundingClientRect().height.toString().concat('px');
}

值得注意的是,在 for 循环中根本没有执行任何操作,我尝试使用一个console.log函数并且没有记录任何内容。

如果它有帮助,这里是元素的 HTML 和 CSS(我没有在这个片段中显示,但我确实有<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0' />):

<body>
 <div id = 'header'>
  <div id = 'header-title'>
   <span id = 'header-icons'>
    <img id = 'icon-layer1' src = '../../assets/logos/layer1.svg'>
    <img id = 'icon-layer2' src = '../../assets/logos/layer2.svg'>
   </span>
   <span id = 'header-text'>Karakaras Portfolio</span>
  </div>
   <div id = 'header-extras'>
    <span id = 'extras-info' class = 'extras-iconlink'>
     <img id = 'icon-info' src = '../../assets/icons/info.svg'>
     <span class = 'extras-iconlink-text'>About</span>
    </span>
    <span id = 'extras-projects' class = 'extras-iconlink'>
     <img id = 'icon-info' src = '../../assets/icons/projects.svg'>
     <span class = 'extras-iconlink-text'>Dev projects</span>
    </span>
   </div>
 </div>
</body>
#header {
 top: 0%;
 left: 0%;
 width: 100%;
 height: 7.5%;
 background-color: #7161ef;
 position: fixed;
}
#header #header-title {
 top: 5%;
 left: 0.15%;
 width: 20%;
 height: 90%;
 background-color: transparent;
 position: absolute;
}
#header #header-title #header-text {
 display: flex;
 top: 5%;
 left: 25%;
 width: 80%;
 height: 90%;
 justify-content: center;
 flex-direction: column;
 background-color: inherit;
 white-space: nowrap;
 position: absolute;
 font-family: 'comfortaabold';
 font-size: 120%;
}
#header #header-extras {
 top: 5%;
 left: 22.65%;
 width: 77.25%;
 height: 90%;
 background-color: transparent;
 position: absolute;
}
#header #header-extras .extras-iconlink {
 display: inline-block;
 top: 10%;
 width: 4%;
 height: 80%;
 background-color: inherit;
 position: absolute;
}
#header #header-extras .extras-iconlink .extras-iconlink-text {
 display: flex;
 top: 0%;
 left: 100%;
 width: 250%;
 height: 100%;
 justify-content: center;
 flex-direction: column;
 background-color: inherit;
 white-space: nowrap;
 position: absolute;
 font-family: 'comfortaabold';
 font-size: 120%;
}

我确信我犯的错误非常愚蠢和明显,我并没有真正做 Web 开发,我主要用 Lua 做游戏开发。

非常感谢所有帮助!

标签: javascripthtmlcssresponsive-design

解决方案


您可能不需要使用 JavaScript 来居中。这主要是一个由 CSS 很好地处理的表示问题。我建议您访问这两个链接,看看在每种情况下您可以使用什么,具体取决于您需要居中的确切位置。不长读。

文本对齐

CSS 居中:完整指南


推荐阅读