當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
js JavaScript实战练习——小球碰撞反弹(详细)
生活随笔
收集整理的這篇文章主要介紹了
js JavaScript实战练习——小球碰撞反弹(详细)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
效果如圖
代碼如下
<!DOCTYPE html> <html><head><meta charset="utf-8"><title></title><style>.wrapper{width: 600px;height: 600px;border: 5px solid black;margin: 0 auto;position: relative;}.wrapper .boll{width: 80px;height: 80px;border-radius: 50%;background-color: red;position: absolute;bottom: 0;left: 0;}.box{text-align: center;}.box button{width: 200px;height: 50px;color:white;font-size: 30px;border: none;background-color: green;}</style></head><body><div class="box"><div class="wrapper"><div class="boll"></div></div><button>開(kāi)始</button></div><script>//獲取容器var _wrapper=document.querySelector(".wrapper");//開(kāi)始按鈕var _button=document.querySelector("button");//小球var _boll=document.querySelector(".boll");_button.onclick=function(){var speedX=1.5; //x速度var speedY=3; //y速度var id=setInterval(function(){//獲取現(xiàn)有的left和top值//如果到最右邊,需要反方向if(_wrapper.clientWidth-_boll.offsetLeft<=_boll.offsetWidth){speedX*=-1;}_boll.style.left=(_boll.offsetLeft+speedX)+"px"//如果到最上邊,需要反方向if(_boll.offsetTop<=0){speedY*=-1;}_boll.style.top=(_boll.offsetTop-speedY)+"px"//到最下邊,需要反向if(_wrapper.clientHeight-_boll.offsetTop<=_boll.offsetHeight){speedY*=-1;}//到最左邊,需要反向if(_boll.offsetLeft<=0){speedX*=-1;}},10)}</script></body> </html>總結(jié)
以上是生活随笔為你收集整理的js JavaScript实战练习——小球碰撞反弹(详细)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 关于句柄的概念
- 下一篇: jade选峰之后怎么去掉_教程丨用Jad