我在试验 CSS3 时发现了一件奇怪的事情。当我将 CSS 动画设置为 height 属性并使用(0,n,0.5,1)
n 大于 0.5 的三次贝塞尔曲线时,元素在动画期间向下移动。
这种解释对吗?在 Firefox 和 Chrome 中似乎是一样的。 现场演示(由于某种原因在 chrome 中不起作用)
我不在 Chrome 中工作,因为您%
在 keframes 中使用而不是px
,而父元素没有设置高度。
并且整体行为是正确的,这是因为您已将元素设置为内联元素,这导致它们默认与基线对齐,虽然该行为在不同速度的动画中最为明显,但您会遇到相同的行为在同步线性运动结束时,即它与三次贝塞尔曲线缓动没有真正的关系。
您可以通过例如更改为vertical-align
来解决此问题top
.box {
width: 50px;
display: inline-block;
vertical-align: top;
background: #5f0;
height: 100px;
border: 1px solid #000;
}
或者通过浮动元素而不是使它们成为内联元素。
.box {
width: 50px;
float: left;
background: #5f0;
height: 100px;
border: 1px solid #000;
}
该演示似乎不适用于 Chrome问题是因为from关键帧的高度是包含元素(在这种情况下)的100%
意思,但在. 两种解决方案,任一设置:100%
<body>
<body>
body {
height:100px;
}
或者
@-webkit-keyframes anim {
from {
height:100px;
}
to {
height:0;
}
}
实际的移动元素问题是因为元素是display:inline-block
但没有vertical-align
设置,所以浏览器使用默认vertical-align:baseline
对齐元素。由于每个块的三次贝塞尔动画属性不同,因此基线在移动,因此元素也在移动。
有关基线移动原因的更多详细信息,请参阅我对为什么此 inline-block 元素具有未垂直对齐的内容的回答。
因此,如果每个块上的动画属性相同,则不会出现您的问题。
对于我的演示,我使用过vertical-align:top;
,但根据您的需要还有其他值。我还设置了animation-fill-mode:forwards
“在动画结束后(由其确定animation-iteration-count
),动画将在动画结束时应用属性值” -来自CSS 文档。
CSS
@keyframes anim {
from {
height: 100px;
}
to {
height: 0;
}
}
@-webkit-keyframes anim {
from {
height:100px;
}
to {
height:0;
}
}
.box {
width: 50px;
display: inline-block;
background: #5f0;
height: 100px;
border: 1px solid #000;
vertical-align:top;
}
.box:first-of-type {
animation: anim 10s cubic-bezier(0, 1, .5, 1);
-webkit-animation: anim 10s cubic-bezier(0, 1, .5, 1) forwards;
}
.box:last-of-type {
animation: anim 10s cubic-bezier(0, .5, .5, 1);
-webkit-animation: anim 10s cubic-bezier(0, .5, .5, 1) forwards;
}
HTML
<div class=box></div>
<div class=box></div>