向后切换很突然
我有一段代码,包含一个向前和向后的 transition。它使用 allow-keywords,因此是为Chrome编写的,尚未支持其他浏览器。
.foo {
transition: width 1s, display 1s;
@starting-style {
width: 0;
}
transition-behavior: allow-discrete;
interpolate-size: allow-keywords;
outline: 1px solid black;
}
body:has(#show:not(:checked)) .foo {
display: none;
width: 0;
/* transition: width 0.5s 0.5s, display 1s; */
}
<label><input type="checkbox" id="show">Click here twice</label>
<div class="foo">foo</div>
但如果我试图通过添加一个 transition,并在 :checked 条件下让向后过渡变得不同,向后过渡就会完全失效(样式会突然改变,没有过渡效果):
.foo {
transition: width 1s, display 1s;
@starting-style {
width: 0;
}
transition-behavior: allow-discrete;
interpolate-size: allow-keywords;
outline: 1px solid black;
}
body:has(#show:not(:checked)) .foo {
display: none;
width: 0;
transition: width 0.5s 0.5s, display 1s;
}
<label><input type="checkbox" id="show">Click here twice</label>
<div class="foo">foo</div>
为什么会这样?
即使两个 transition 的值完全相同,也会发生这种情况。
解决方案
transition 是对多项属性的简写,其中包括 transition-behavior,并会覆盖该属性。你必须重新显式定义 transition-behavior:
.foo {
transition: width 1s, display 1s;
@starting-style {
width: 0;
}
transition-behavior: allow-discrete;
interpolate-size: allow-keywords;
outline: 1px solid black;
}
body:has(#show:not(:checked)) .foo {
display: none;
width: 0;
transition: width 0.5s 0.5s, display 1s;
transition-behavior: allow-discrete;
}
<label><input type="checkbox" id="show">Click here twice</label>
<div class="foo">foo</div>
理想情况下,将 transition-behavior 合并到 transition 中。这样就能更清楚地知道需要为哪些CSS属性自定义 transition-behavior。
.foo {
transition: width 1s, display 1s allow-discrete;
@starting-style {
width: 0;
}
interpolate-size: allow-keywords;
outline: 1px solid black;
}
body:has(#show:not(:checked)) .foo {
display: none;
width: 0;
transition: width 0.5s 0.5s, display 1s allow-discrete;
}
<label><input type="checkbox" id="show">Click here twice</label>
<div class="foo">foo</div>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。