为什么我的字体尺寸不使用香草JS调整?
我在这里有这个小代码,通过控制台日志,我可以看到它显然已更改,但在显示器上没有更改。可能出了什么问题?
下方的JS香草
const gameItem = document.querySelectorAll('.game-item');
const gameItemS = document.querySelector('.game-item');
document.addEventListener('DOMContentLoaded', () => {
titleSize(gameItem);
});
const titleSize = (gameItem) => {
[...gameItem].forEach((title) => {
let textSize = window
.getComputedStyle(title, null)
.getPropertyValue('font-size');
let gameTitle = title.innerText;
// console.log(gameTitle, gameTitle.length, textSize);
if (gameTitle.length > 7) {
textSize = '5px';
console.log(
'The font on this was changed: ' + gameTitle,
gameTitle.length,
textSize
);
}
});
};
下面HTML
<section class="games">
<h1>Games</h1>
<ol class="container">
<li class="game-item">Halo<img src="" /></li>
<li class="game-item">Pokemon<img src="" /></li>
<li class="game-item">
Animal Crossing<img src="" />
</li>
<li class="game-item">Genshin Impact<img src="" /></li>
<li class="game-item">Skyrim<img src="" /></li>
</ol>
</section>
I have this little code here and by the console logs I can see it is apparently changed but on the display it is not changing. What could be going wrong ?
JS vanilla below
const gameItem = document.querySelectorAll('.game-item');
const gameItemS = document.querySelector('.game-item');
document.addEventListener('DOMContentLoaded', () => {
titleSize(gameItem);
});
const titleSize = (gameItem) => {
[...gameItem].forEach((title) => {
let textSize = window
.getComputedStyle(title, null)
.getPropertyValue('font-size');
let gameTitle = title.innerText;
// console.log(gameTitle, gameTitle.length, textSize);
if (gameTitle.length > 7) {
textSize = '5px';
console.log(
'The font on this was changed: ' + gameTitle,
gameTitle.length,
textSize
);
}
});
};
html below
<section class="games">
<h1>Games</h1>
<ol class="container">
<li class="game-item">Halo<img src="" /></li>
<li class="game-item">Pokemon<img src="" /></li>
<li class="game-item">
Animal Crossing<img src="" />
</li>
<li class="game-item">Genshin Impact<img src="" /></li>
<li class="game-item">Skyrim<img src="" /></li>
</ol>
</section>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
分配给
textsize
只会更改该变量的值,它对元素没有任何影响。当您进行时,让TextSize = /*....../..getPropertyValue('font-size');
,它只是将来自计算样式对象的值复制到变量中。变量与计算样式对象之间没有持续的链接。 (即使有,分配给计算样式对象不会更改元素。)要更改元素的样式,您也必须分配给
title.Style.fontsize
(或) title.Style [“ font-size”]
):Assigning to
textSize
just changes the value of that variable, it doesn't have any effect on the element. When you dolet textSize = /*...*/.getPropertyValue('font-size');
, that just copies the value from the computed style object into the variable. There's no ongoing link between the variable and that computed style object. (Even if there were, assigning to the computed style object won't change the element.)To change the element's style, you'd have to assign to
title.style.fontSize
(ortitle.style["font-size"]
):