我有两个嵌套元素:A
和 B
。外部元素 A
与内部元素 B
大小相同。元素 B
包含一些文本。这两个元素都有一个持续时间为一秒的 CSS 过渡。悬停时,A
更改文本颜色,而 B
更改背景颜色。
#A {
color: red;
transition: all 1s;
}
#B {
font-size: 100px;
background-color: red;
transition: all 1s;
}
#A:hover {
color: green;
}
#B:hover {
background-color: green;
}
<div id="A">
<div id="B">Example Text</div>
</div>
我预计转换会同时完成,但是背景转换在文本转换之前完成。是什么导致了这种行为?
最佳答案
这是由 this Chrome bug 引起的(和 this Webkit one )。
基本上,它们会在每个级别触发一次继承属性的转换,并且每个级别都会将下一个级别延迟转换的持续时间。
您可以通过确保继承的属性(此处为 color
)仅转换一次来避免此问题:
#A {
color: red;
transition: all 1s;
}
#B {
font-size: 100px;
background-color: red;
transition: background-color 1s; /* limit this transition to bg-color only */
}
#A:hover {
color: green;
}
#B:hover {
background-color: green;
}
<div id="A">
<div id="B">Example Text</div>
</div>
或
#A {
color: red;
}
#B {
font-size: 100px;
background-color: red;
transition: all 1s; /* set the transition only on the child */
}
#A:hover {
color: green;
}
#B:hover {
background-color: green;
}
<div id="A">
<div id="B">Example Text</div>
</div>
关于html - 为什么相同持续时间的转换需要不同的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75231666/