使用javascript连续旋转图像



我想写一个javascript通过点击按钮连续旋转图像。我可以通过点击来实现部分旋转。我认为我应该递归地调用这个函数来获得一个连续的旋转,但我不知道怎么做。以下是我的代码:

<html>
<head>
<title>Image Rotation</title>
</head>
<body>
<button id="rotate">Rotate</button>
<img src="images/circle.png" id="sample" ;" alt="" />

</body>
<script>
var rotation = 0;

document.querySelector("#rotate").addEventListener('click', function() {

rotation += 90;

document.querySelector("#sample").style.transform = 'rotate(' + rotation + 'deg)';
});

</script>
</html>

在你的CSS文件中添加一个类

.rotating {
animation: rotate 1s infinite;
}
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}

,然后用javascript把这个类添加到元素

document.querySelector("#rotate").addEventListener('click', function() {
document.querySelector("#sample").classList.add('rotating')
});

最新更新