为什么CSS动画会突然停止



我发现了一个新的主题CSS动画。我试着实现了一些例子。在下面的代码中。有2个事件处理程序与元素关联。它们都会更改同一元素的动画属性。第一次启动任何事件时,动画都是平滑的。但在那之后,这两件事都戛然而止。我怎样才能把它弄平?

<!DOCTYPE html>
<html>
<head>
<style> 
div {
width: 100px;
height: 100px;
background: red;
position: relative;

}
section {
width: 100px;
height: 100px;
background: aqua;
}
@keyframes mymove {
from {top: 0px;}
to {top: 200px;}
}
</style>
</head>
<body>
<h1>The @keyframes Rule</h1>
<p><strong>Note:</strong> The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.</p>
<section></section>
<div></div>
</body>
<script>
document.querySelector('div').onclick = () => {
document.querySelector('div').style.animation = 'mymove 2s linear forwards';
}
document.querySelector('section').onclick = () => {
document.querySelector('div').style.animation = 'mymove 2s linear reverse backwards';
}
</script>
</html>

这就是您想要的结果吗?请注意,我添加了第二个关键帧声明。

<!DOCTYPE html>
<html>
<head>
<style> 
div {
width: 100px;
height: 100px;
background: red;
position: relative;

}
section {
width: 100px;
height: 100px;
background: aqua;
}
@keyframes mymove {
from {top: 0px;}
to {top: 200px;}
}
@keyframes mymove1 {
from {top: 0px;}
to {top: 200px;}
}
</style>
</head>
<body>
<h1>The @keyframes Rule</h1>
<p><strong>Note:</strong> The @keyframes rule is not supported in Internet Explorer 9 and earlier versions.</p>
<section></section>
<div></div>
</body>
<script>
document.querySelector('div').onclick = () => {
document.querySelector('div').style.animation = 'mymove 2s linear forwards';
}
document.querySelector('section').onclick = () => {
document.querySelector('div').style.animation = 'mymove1 2s linear reverse backwards';
}
</script>
</html>

更新:

我能找到的原始代码不工作的最好原因是:

动画名称属性定义应用的动画列表。每个名称都用于选择提供动画特性值的关键帧at规则。如果名称与规则中的任何关键帧都不匹配,则没有要设置动画的属性,动画也不会执行。此外,如果动画名称为none,则不会有动画。这可用于覆盖来自级联的任何动画。如果多个动画试图修改同一属性,则最靠近名称列表末尾的动画获胜。按名称列出的每个动画都应具有下面列出的其他动画属性的相应值。如果其他动画特性的值列表的长度不相同,则动画名称列表的长度将确定启动动画时检查的每个列表中的项目数。列表从第一个值开始匹配:不使用末尾的多余值。如果其他属性之一没有足够的逗号分隔值来匹配动画名称的值数,UA必须通过重复值列表来计算其使用的值,直到有足够的值为止。这种截断或重复不会影响计算值。注意:这类似于background-*属性的行为,背景图像类似于动画名称。

https://drafts.csswg.org/css-animations/#animation-名称

最新更新