写一段有趣的JavaScript代码
时间: 2023-06-12 19:06:35 浏览: 53
好的,给你写一个简单的小游戏,让你在页面上点击一个按钮,让一个小球在页面上跳动:
```javascript
let ball = document.createElement('div');
ball.style.width = '50px';
ball.style.height = '50px';
ball.style.borderRadius = '50%';
ball.style.backgroundColor = 'red';
ball.style.position = 'absolute';
ball.style.left = '0';
ball.style.top = '0';
document.body.appendChild(ball);
let direction = 1;
let speed = 10;
ball.addEventListener('click', function() {
direction = direction * -1;
});
setInterval(function() {
let currentLeft = parseInt(ball.style.left);
let newLeft = currentLeft + (speed * direction);
if (newLeft > window.innerWidth - 50 || newLeft < 0) {
direction = direction * -1;
}
ball.style.left = newLeft + 'px';
}, 50);
```
这段代码会创建一个红色的小球,并且让它在页面上左右移动,当你点击小球时,它会改变方向。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)