为什么我的字体大小不能用 vanilla js 调整?

Why is my font size not adjusting with vanilla 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>

分配给 textSize 只是更改该变量的值,它对元素没有任何影响。当您执行 let textSize = /*...*/.getPropertyValue('font-size'); 时,这只是将计算样式对象中的值复制到变量中。变量和计算出的样式对象之间没有持续的 link。 (即使有,分配给计算样式对象也不会更改元素。)

要更改元素的样式,您必须分配给 title.style.fontSize(或 title.style["font-size"]):

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) {
            title.style.fontSize = '5px';
            console.log(
                'The font on this was changed: ' + gameTitle,
                gameTitle.length,
                textSize
            );
        }
    });
};
<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>