js旋转动画
时间: 2023-08-05 15:07:29 浏览: 56
你可以使用CSS3的`transform`属性来实现旋转动画。首先,需要定义一个HTML元素,例如一个`div`元素,然后使用CSS样式来定义它的大小、颜色等基本属性。接下来,使用`transform`属性来定义旋转效果。
下面是使用JavaScript在页面上创建一个`div`元素,并对其应用旋转动画的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>JS Rotation Animation</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
animation-name: rotate;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<script>
// create a new div element
var div = document.createElement("div");
div.id = "box";
// add the div element to the body
document.body.appendChild(div);
</script>
</body>
</html>
```
在上面的代码中,`#box`元素定义了基本样式,`transform: translate(-50%, -50%)`用于将元素水平垂直居中,`animation-name`指定了动画名称为`rotate`,`animation-duration`指定动画持续时间为2秒,`animation-iteration-count`指定动画循环次数为无限次,`animation-timing-function`指定动画时间函数为线性(即匀速运动)。`@keyframes`定义了动画关键帧,从0度旋转到360度。
你可以根据自己的需要调整`transform`属性的参数、动画名称和持续时间等参数来实现不同的旋转动画效果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)