我正在使用 CSS 动画在页面加载时滑入一个 div。 ( Chrome )
我使用 animation-fill-mode: forwards;
来保持新状态。
从那里我想要一个简单的悬停动画,它使用 transform:scale(2);
并让它过渡超过 1 秒。
我的 CSS:
.box{
background-color:blue;
width:100px;
height:100px;
margin: 0 auto;
animation-name: test;
animation-duration: 3s;
animation-fill-mode: forwards;
transition: 1s ease;
}
@keyframes test{
0% {
transform: translate(-200px)
}
100% {
transform: translate(0px);
}
}
.box:hover{
transform: scale(2);
}
如果我在悬停时使用一个简单的更改,比如 border-radius
它会起作用:
.box{
transition: border-radius 0.25s ease;
}
.box:hover{
border-radius: 100%;
}
初始 CSS 动画以某种方式干扰了元素悬停状态的变换/过渡。
如果我更改悬停以删除 animation-fill-mode
,transform
将起作用,但过渡不起作用:
.box:hover{
animation-fill-mode:none;
border-radius: 100%;
}
有什么想法吗?
最佳答案
为什么当动画填充模式为向前时转换不起作用?
根据 W3C pec : (重点是我的)
By default, an animation will not affect property values between the time it is applied (the ‘animation-name’ property is set on an element) and the time it begins execution (which is determined by the ‘animation-delay’ property). Also, by default an animation does not affect property values after the animation ends (determined by the ‘animation-duration’ property). The ‘animation-fill-mode’ property can override this behavior.
If the value for ‘animation-fill-mode’ is ‘forwards’, then after the animation ends (as determined by its ‘animation-iteration-count’), the animation will apply the property values for the time the animation ended.
上面的意思是,即使在动画结束后,UA 也必须在元素上应用和维护 transform
。这有点意味着动画中提到的 transform
优先,因此 :hover
状态中提到的 transform
没有效果.
当应用 animation-fill-mode: none
或 animation-fill-mode: backwards
时,UA 不必在动画完成后保持转换后的状态结束(意味着它有点像 transform: none
),因此 :hover
选择器中的 transform
起作用。
此行为在最新版本的 Chrome 和 Firefox 中是一致的。在 IE11 和 Edge 中,无论为 animation-fill-mode
提供什么值,在 :hover
选择器中指定的 transform
都不起作用> 属性(property)。
为什么即使将填充模式更改为无,过渡也不起作用?
我不确定 CodePen 中的代码是否是原始代码,或者您是否为测试做了任何更改,但是该演示中的 transition
属性被错误地指定,这就是为什么 transition 没有的原因发生。
存在的代码是:
transition: scale 1s ease;
但是 scale
不是需要转换的属性。这只是需要完成的转换类型。 property 是 transform
因此代码应该如下所示:
transition: transform 1s ease;
如果您进行此更改,则当 animation-fill-mode
发生更改时,transition
将起作用。
关于动画填充模式 : forwards 后悬停时的 CSS 变换和过渡不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36551715/