我正在尝试建立我的第一个响应式网站,但我遇到了一些问题。
特别是,我需要一些文本居中,但当我在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函数,但没有记录任何内容。
如果有帮助,这里是元素的超文本标记语言和样式表(我没有在这段代码中显示,但我有<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做gamedev。
非常感谢大家的帮助!
发布于 2019-09-23 02:39:28
您可能不需要使用JavaScript来居中。这主要是一个由CSS很好地处理的表示问题。我建议你转到这两个链接,看看你可以在每种情况下使用什么,这取决于你到底需要什么居中。并不是一个很长的阅读。
发布于 2019-09-23 02:53:18
您可以根据窗口大小设置字体的大小。例如,要在所有小于600px的屏幕上将字体大小设置为20px,您可以使用以下CSS:
@media (max-width: 600px) {
#header {
font-size: 20px;
}}https://stackoverflow.com/questions/58052179
复制相似问题