js和css动画使图片点击开始转动点击停止就停点击加速就加速点击减速就减速
以下是一个实现该功能的示例代码:
HTML:
<img src="image.jpg" id="image" onclick="toggleAnimation()" />
CSS:
#image {
transition: transform 1s ease-out;
}
.rotate {
transform: rotate(360deg);
}
JavaScript:
var image = document.getElementById("image");
var isAnimating = false;
var speed = 1;
function toggleAnimation() {
if (isAnimating) {
clearInterval(intervalId);
isAnimating = false;
} else {
intervalId = setInterval(rotateImage, 10 / speed);
isAnimating = true;
}
}
function rotateImage() {
var currentRotation = parseInt(image.style.transform.replace("rotate(", "").replace("deg)", ""));
var newRotation = currentRotation + 1;
if (newRotation >= 360) {
newRotation = 0;
}
image.style.transform = "rotate(" + newRotation + "deg)";
}
function increaseSpeed() {
speed += 0.1;
if (isAnimating) {
clearInterval(intervalId);
intervalId = setInterval(rotateImage, 10 / speed);
}
}
function decreaseSpeed() {
speed -= 0.1;
if (speed < 0.1) {
speed = 0.1;
}
if (isAnimating) {
clearInterval(intervalId);
intervalId = setInterval(rotateImage, 10 / speed);
}
}
在上面的代码中,我们首先定义了一个变量isAnimating来表示图片是否正在旋转。然后定义了一个变量speed来表示旋转速度,初始值为1。toggleAnimation函数用于切换图片的旋转状态。如果图片正在旋转,则停止旋转;否则,开始旋转。rotateImage函数用于实现图片的旋转动画。它会获取当前旋转角度,将其加1,然后将新的旋转角度应用到图片上。如果旋转角度超过了360度,则将其重置为0度。increaseSpeed和decreaseSpeed函数分别用于增加和减少旋转速度。如果图片正在旋转,则先停止旋转,然后重新启动旋转动画,以应用新的旋转速度
原文地址: https://www.cveoy.top/t/topic/cnnw 著作权归作者所有。请勿转载和采集!