在它们停止工作后恢复过渡效果

Reviving transition effects after they stop working

本文关键字:恢复 过渡效果 停止工作      更新时间:2024-04-13

好的,如果通过CSS在样式上设置转换,那么只要样式没有被Javascript更改,它就会工作并保持工作(然后转换停止),即使Javascript将原始属性恢复到以前的值。

在一种风格被"触动"之后,有没有办法恢复过渡?

例如,一旦Javascript将宽度设置为100px(这是CSS值),转换就会停止。

var el = document.getElementById("test");
el.style.width = "100px";
div {
    width: 100px;
    height: 100px;
    background: red;
    -webkit-transition: width 2s; /* For Safari 3.1 to 6.0 */
    transition: width 2s;
}
div:hover {
    width: 300px;
}
<div id="test"></div>

当您将宽度与el.style.width = "100px"硬连接时,它将覆盖您的div:hover CSS规则,因此它将不再具有优先级。

您需要增加:hover CSS规则的优先级,使其仍然有效。你可以通过多种方式做到这一点。一种方法是使用!important。通常,我不喜欢使用!important,但在这种情况下,如果没有它,很难覆盖直接指定样式的优先级

div:hover {
    width: 300px !important;
}

您可以在这里阅读如何计算CSS的特异性,以确定什么获得优先权。不幸的是,直接指定的样式规则具有很高的优先级。

这是一个工作演示:

var el = document.getElementById("test");
el.style.width = "100px";
div {
    width: 100px;
    height: 100px;
    background: red;
    -webkit-transition: width 2s; /* For Safari 3.1 to 6.0 */
    transition: width 2s;
}
div:hover {
    width: 300px !important;
}
<div id="test"></div>

您可以用!important 覆盖内联样式

div:hover {
    width: 300px !important;
}

它本身并没有停止,JavaScript只是将宽度放置为具有最高特异性的内联CSS(!important除外),因此悬停宽度将不起作用,因为其特异性较弱。一种解决方法是使用!important,但我不建议这样做。尝试删除JS样式或使用类转换

var el = document.getElementById("test");
el.style.width = "100px";
div {
    width: 100px;
    height: 100px;
    background: red;
    -webkit-transition: width 2s; /* For Safari 3.1 to 6.0 */
    transition: width 2s;
}
div:hover {
    width: 300px !important;
}
<div id="test"></div>