我有一个 <button>
元素想要当这个元素被点击时,按钮向下移动 200px
在 onclick
中使用此代码添加类的按钮事件,因此动画将运行:
JS
function anime() {
var element = document.getElementById("tagd");
element.classList.toggle("visible");
}
HTML
<button onclick="anime()" id="tagd">
CSS
.visible {
-webkit-animation: myfirst 5s 2; /* Safari 4.0 - 8.0 */
-webkit-animation-direction: normal; /* Safari 4.0 - 8.0 */
animation: myfirst 5s 2;
animation-direction: normal;
position: relative;
}
/* Safari 4.0 - 8.0 */
@-webkit-keyframes myfirst {
0% {top: 0px;}
25% {top: 50px;}
50% {top: 100px;}
75% {top: 150px;}
100% {top: 200px;}
}
@keyframes myfirst {
0% {top: 0px;}
25% {top: 50px;}
50% {top: 100px;}
75% {top: 150px;}
100% {top: 200px;}
}
所以问题是:
- 动画下降,然后回到第一个位置。
- 动画播放不流畅(运行会发现一步步播放不流畅)
最佳答案
因为你只是改变按钮的位置,我可以建议你以下
#tagd{
transition: 5s transform
}
#tagd.visible{
transform: translateY(200px)
}
动画非常简单,因此使用它可以提高代码的可读性。有点微不足道,但使用“翻译”而不是“顶部”也可以提高视觉效果。
如果您愿意,请阅读更多相关信息: https://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/
关于CSS 动画播放不流畅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56983336/