Jea*_*eri 7 css keyframe css-animations
使用 css@keyframes我试图在单击元素时将一些动画附加到元素上。
.animate {
animation-name: action;
animation-duration: 2s;
animation-timing-function: linear;
background-color: green;
}
@keyframes action {
0% {
background-color: gray;
}
50% {
background-color: red;
}
100% {
background-color: green;
}
}
Run Code Online (Sandbox Code Playgroud)
在.animate类上点击,并将盒子从灰色动画绿色。但是现在我想再次单击它时将动画恢复为灰色(切换功能)。我尝试使用相同的动画,animation-direction: reverse但没有播放动画。动画最初不应该播放(我遇到过几次)。任何建议我如何实现这一目标?
我会考虑使用该animation-play-state属性并使用infiniteand alternate。这个想法是运行动画并在它结束时停止它,然后再次运行它,依此类推:
const div = document.querySelector('.target')
div.addEventListener('click', (e) => {
div.classList.add('play');
setTimeout(function() {
div.classList.remove('play');
},2000)
})Run Code Online (Sandbox Code Playgroud)
.target {
width: 100px;
height: 100px;
background-color: gray;
cursor: pointer;
animation: action 2s linear alternate infinite;
animation-play-state:paused;
}
.play {
animation-play-state:running;
}
@keyframes action {
0% {
background-color: gray;
}
50% {
background-color: red;
}
100% {
background-color: green;
}
}Run Code Online (Sandbox Code Playgroud)
<div class="target">
</div>Run Code Online (Sandbox Code Playgroud)
用动画处理这种开/关变化总是很棘手的,并且很难平滑、无缝地处理重复的变化。
对于您的情况,我建议将其更改为单个转换。在这种情况下,浏览器可以更好地处理开/关部分。要通过过渡实现背景颜色的双重变化,请创建具有 3 种颜色的渐变,并更改渐变位置:
const div = document.querySelector('.test')
div.addEventListener('click', (e) => {
div.classList.toggle('play');
})Run Code Online (Sandbox Code Playgroud)
.test {
border: solid 1px black;
margin: 10px;
height: 100px;
width: 100px;
background-image: linear-gradient(gray 0%, gray 20%, blue 40%, blue 60%,
red 80%, red 100%);
background-size: 100% 9000%;
background-repeat: no-repeat;
background-position: center top;
transition: background-position .3s;
}
.play {
background-position: center bottom;
}Run Code Online (Sandbox Code Playgroud)
<div class="test">
</div>Run Code Online (Sandbox Code Playgroud)