Css 如何从 :hover 和正常过渡,但在页面加载时更改值而不进行过渡

Css how to have transitions from :hover and normal, but change the value without transition when the page loads

基本上我有这个代码:

#test {
    color: white;
    transition: all 1s;
    display: inline;
}

#test:hover {
    color: red;
    transition: all 1s;
}

它按预期工作。当我将鼠标悬停在文本上时,它会变成红色,然后当我停止悬停在它上面时,它又会变回白色。但问题是,由于默认为黑色,当页面开始加载时,您会看到从黑色到白色的过渡。我需要的是文本从一开始就是白色的,然后让所有的转换都能正常工作

编辑:在 https://martinGITHUBER.github.io 上似乎一切正常,问题只发生在本地,所以我想我只需要处理 Chrome 很奇怪的事情

设置#test的parent的css。因为 HTML 标签继承了他的 parent 的 CSS 属性。

#parent-container {
        color: white;
    }

    #test {
        color: white;
        transition: all 1s;
        display: inline;
    }

    #test:hover {
        color: red;
        transition: all 1s;
    }
<div id='parent-container'>
    <span id='test'>hello</span>
</div>

我克隆了您的存储库并设法在有限的情况下重现了该问题。似乎在 Chrome 中(也许其他一些非 Windows 浏览器也是如此,我无法检查)当您直接在浏览器中打开 index.html 文件时,它不会加载head 中的元素在第一次绘制发生之前的时间。这意味着 CSS 应用到页面的时间太晚,将触发转换。

解决方案是使用合适的开发服务器,这将为您带来许多额外的好处,例如热重载,并且如本示例所要求的那样,一个真实的浏览器环境,其中资源是获取而不是直接链接的由文件系统。如果您使用 VSCode,那么 Live Server plugin is a good tool, otherwise you can install simple Command Line tools like serve 或各种用于打包器的插件,例如 webpack 和 rollup,如果您的项目使用这些插件。