我有一个链接,我希望在单击时将其边框从1px设置为5px,在动画的结尾,我希望1px保持不变,我在使用向后的animation-fill-mode,但是我看到1px的边框没有动画完成后应用。
document.querySelector('a').onclick = function() {
this.classList.add('border-g');
}
/* Styles go here */
body {
margin: 100px;
}
a {
border: 1px solid transparent;
display: inline-block;
padding: 20px;
}
.border-g {
-webkit-animation: border-grow 0.5s;
animation: border-grow 0.5s;
-webkit-animation-delay: 1s;
animation-delay: 1s;
-webkit-animation-fill-mode: backwards;
animation-fill-mode: backwards;
}
@-webkit-keyframes border-grow {
from {
border: 1px solid #D74C43;
}
to {
border: 5px solid #D74C43;
}
}
@keyframes border-grow {
from {
border: 1px solid #D74C43;
}
to {
border: 5px solid #D74C43;
}
}
<a>Hello world</a>
最佳答案
在这种情况下,您必须首先在CSS中定义最终状态。
然后在动画中定义新的起点
body {
margin: 100px;
}
a {
border: 1px solid #D74C43;
/* end like this */
display: inline-block;
padding: 20px;
-webkit-animation: border-grow 0.5s;
animation: border-grow 0.5s;
-webkit-animation-delay: 1s;
animation-delay: 1s;
-webkit-animation-fill-mode: backwards;
animation-fill-mode: backwards;
}
@-webkit-keyframes border-grow {
from {
border: 1px solid transparent;
/* starts like this */
}
to {
border: 5px solid #D74C43;
/* animation ends then switches to final state */
}
}
@keyframes border-grow {
from {
border: 1px solid transparent;
}
to {
border: 5px solid #D74C43;
}
}
<a>Hello world</a>
编辑
要解决您更新的问题...默认状态将需要应用于
border-g
类。否则答案仍然像以前一样。
document.querySelector('a').onclick = function() {
this.classList.add('border-g');
}
body {
margin: 100px;
}
a {
display: inline-block;
padding: 20px;
}
a.border-g {
border: 1px solid #D74C43;
-webkit-animation: border-grow 0.5s;
animation: border-grow 0.5s;
-webkit-animation-delay: 1s;
animation-delay: 1s;
-webkit-animation-fill-mode: backwards;
animation-fill-mode: backwards;
}
@-webkit-keyframes border-grow {
from {
border: 1px solid transparent;
}
to {
border: 5px solid #D74C43;
}
}
@keyframes border-grow {
from {
border: 1px solid transparent;
}
to {
border: 5px solid #D74C43;
}
}
<a>Hello world</a>