Если мы объединим его с событием animationiteration
, мы сможем это сделать.
const spin = document.querySelector(".spin");
let iterationCount = 0;
let isMouseover = 0;
spin.addEventListener('animationiteration', () => {
iterationCount = 1;
if (iterationCount && isMouseover) {
spin.classList.remove("animation");
} else {
iterationCount = 0;
}
});
spin.addEventListener("mouseover", () => {
isMouseover = 1;
});
spin.addEventListener("mouseout", () => {
isMouseover = 0;
spin.classList.add("animation");
});
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.spin {
height: 100px;
width: 100px;
background: yellow;
border-right: 4px solid green;
border-left: 4px solid red;
border-top: 4px solid black;
border-bottom: 4px solid blue;
}
.spin.animation {
animation: spin .8s linear .15s infinite;
}
<div class="spin animation"></div>
Также работает с щелчком:
const spin = document.querySelector(".spin");
let iterationCount = 0;
let isClicked = 0;
spin.addEventListener('animationiteration', () => {
iterationCount = 1;
if (iterationCount && isClicked) {
spin.classList.remove("animation");
} else {
iterationCount = 0;
}
});
spin.addEventListener("click", () => {
if (isClicked) {
isClicked = 0;
spin.classList.add("animation");
} else {
isClicked = 1;
}
});
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.spin {
height: 100px;
width: 100px;
background: yellow;
border-right: 4px solid green;
border-left: 4px solid red;
border-top: 4px solid black;
border-bottom: 4px solid blue;
}
.spin.animation {
animation: spin .8s linear .15s infinite;
}
<div class="spin animation"></div>