js实现一个小球从页面左侧向右侧的三次平移
时间: 2024-05-03 08:23:34 浏览: 21
以下是js实现小球从页面左侧向右侧的三次平移的代码:
HTML代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>小球三次平移</title>
<style type="text/css">
#ball {
position: absolute;
width: 50px;
height: 50px;
border-radius: 50%;
background-color: red;
}
</style>
</head>
<body>
<div id="ball"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
```
JavaScript代码:
```javascript
var ball = document.getElementById("ball");
// 第一次平移
var firstTranslation = "translateX(200px)";
// 第二次平移
var secondTranslation = "translateX(400px) translateY(100px)";
// 第三次平移
var thirdTranslation = "translateX(600px) translateY(250px)";
// 设置小球初始位置
ball.style.transform = firstTranslation;
// 执行第一次平移
setTimeout(function() {
ball.style.transform = firstTranslation + " " + secondTranslation;
}, 1000);
// 执行第二次平移
setTimeout(function() {
ball.style.transform = firstTranslation + " " + secondTranslation + " " + thirdTranslation;
}, 2000);
```
解释说明:
1. 首先获取HTML中的小球元素。
2. 定义三次平移的变量:第一次平移向右200px,第二次平移向右400px和向下100px,第三次平移向右600px和向下250px。
3. 设置小球初始位置为第一次平移的位置。
4. 使用setTimeout函数,延迟1秒后执行第一次平移,将小球的transform属性设置为第一次平移和第二次平移的组合。
5. 使用setTimeout函数,延迟2秒后执行第二次平移,将小球的transform属性设置为三次平移的组合。
6. 小球完成三次平移效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)