gpt4 book ai didi

javascript - 在 Javascript 中使用类名的动画

转载 作者:行者123 更新时间:2023-11-28 18:10:16 26 4
gpt4 key购买 nike

我正在尝试通过单击按钮向其添加 CSS 类名称来为 div 设置动画。但这只适用于第一次。下次我单击按钮并添加 CSS 类名称时,它不会为 div 设置动画。我在这里做错了什么?

<head>
<script>
function abc() {
document.getElementById("a").className = "";
document.getElementById("a").className = document.getElementById("a").className + " b";
}
</script>
<style>
#a {
width:100px;
height:100px;
background:red;
position:relative;
}
.b {
animation-name:myfirst;
animation-duration:5s;
animation-timing-function:linear;
animation-delay:2s;
animation-iteration-count:1;
animation-direction:alternate;
animation-play-state:running;
}

@keyframes myfirst
{
0% {background:red; left:0px; top:0px;}
25% {background:yellow; left:200px; top:0px;}
50% {background:blue; left:200px; top:200px;}
75% {background:green; left:0px; top:200px;}
100% {background:red; left:0px; top:0px;}
}

@-webkit-keyframes myfirst /* Safari and Chrome */
{
0% {background:red; left:0px; top:0px;}
25% {background:yellow; left:200px; top:0px;}
50% {background:blue; left:200px; top:200px;}
75% {background:green; left:0px; top:200px;}
100% {background:red; left:0px; top:0px;}
}
</style>
</head>

<body>

<div id="a" class="c"></div>
<button onclick="abc()">Click</button>

</body>

最佳答案

给定元素上的类是一个集合,因此添加一个已经存在的类不会改变任何东西。使用 JavaScript 可能会更好地完成这种动画。 (实际上,CSS 动画就像 CSS 中的任何东西一样——它取决于状态,而不是 Action 。)

还是我理解错了?是不停的问题吗?

由于您正在使用动画,因此假设 classList 支持可能是安全的,因此:

document.getElementById("a").classList.toggle("b");

关于javascript - 在 Javascript 中使用类名的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18804555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com