我一直在尝试放置一些基本的 CSS3 动画。目标是在按钮的单击事件上切换一个类,并根据添加的类为 div 设置动画。该代码对于 Firefox 中切换的第一次迭代非常有效,但对于 Chrome 等其他浏览器以及 Firefox 中的下一次迭代,转换会在眨眼间切换。请帮助我找出问题所在。
片段:
$('button').click(function() {
$('div').toggleClass('clicked');
});
div {
background-color: #ccc;
height: 100px;
width: 100px;
transition-property: top, left;
transition-duration: 1s;
transition-timing-function: linear;
position: relative;
top: 0;
left: 0;
}
.clicked {
animation-name: clicked;
animation-duration: 1s;
animation-timing-function: linear;
animation-fill-mode: forwards;
}
@keyframes clicked {
0% {
top: 0;
left: 0;
}
100% {
top: 100px;
left: 100px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">Click Me!</button>
<div></div>
我也准备了一把 fiddle here .
最佳答案
这是 Chrome 的一种已知行为。 Firefox 似乎确实能够通过过渡平滑地处理动画的移除,但 Chrome 不会这样做。我之前也曾在 this thread 中看到过这种行为.
为什么移除动画不适用于 Chrome 中的过渡?
虽然我不能提供 100% 万无一失的解释为什么会发生这种情况,但我们可以根据 this HTML5Rocks article about Accelerated rendering in Chrome 在一定程度上对其进行解码。和 this one about GPU accelerated compositing in Chrome .
似乎发生的是该元素获得了自己的渲染层,因为它在其上设置了显式位置属性。当一个图层(或其中的一部分)因动画而失效时,Chrome 只会重新绘制受更改影响的图层。当您打开 Chrome 开发者控制台时,打开“Show Paint Rects”选项,您会看到当动画发生时 Chrome 只绘制正在动画的实际元素。
但是,在动画的开始和结束时,整个页面都会重新绘制,这会将元素立即放回其原始位置,从而覆盖过渡行为。
$('button').click(function(){
$('div').toggleClass('clicked');
});
div{
background-color: #ccc;
height: 100px;
width: 100px;
transition-property: top, left;
transition-duration: 1s;
transition-timing-function: linear;
position: relative;
top: 0;
left: 0;
}
.clicked{
animation-name: clicked;
animation-duration: 1s;
animation-timing-function: linear;
animation-fill-mode: forwards;
}
@keyframes clicked{
0% {top: 0; left: 0;}
100% {top: 100px; left: 100px;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">Click Me!</button>
<div></div>
解决方案是什么?
由于您的运动实际上是从一个位置到另一个位置的线性运动,因此您无需任何动画即可实现。我们所需要做的就是使用 translate
转换并将元素移动所需的编号。打开类时的像素数。由于通过另一个选择器将过渡分配给元素,因此移动将以线性方式发生。当关闭类时,由于元素上的过渡,元素再次以线性方式移回其原始位置。
$('button').click(function() {
$('div').toggleClass('clicked');
});
div {
background-color: #ccc;
height: 100px;
width: 100px;
transition-property: transform;
transition-duration: 1s;
transition-timing-function: linear;
position: relative;
top: 0;
left: 0;
}
.clicked {
transform: translate(100px, 100px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<button type="button">Click Me!</button>
<div></div>
关于javascript - 动画和过渡的组合无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32142484/