JavaScript實(shí)現(xiàn)多球運(yùn)動(dòng)效果
本文實(shí)例為大家分享了JavaScript實(shí)現(xiàn)多球運(yùn)動(dòng)的具體代碼,供大家參考,具體內(nèi)容如下
代碼如下:
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>多球運(yùn)動(dòng)</title> <style> *{margin:0;padding:0;} body{background-color: #90f;} .ball{position: absolute;left:0;top:0;width:100px;height:100px;background: #f0f;border-radius: 50%;} </style></head><body> <script> run(22)//封裝 //定義速度 var speed; function run(num){ //創(chuàng)建出num個(gè)div for(var i=0;i<num;i++){//[2,11) 隨機(jī)速度speed = Math.floor(Math.random()*9+2);//創(chuàng)建生成節(jié)點(diǎn)var div = document.createElement('div');//添加類名div.className = ’ball’//自定義屬性保存值div.speedX = Math.floor(Math.random()*9+2)div.speedY = Math.floor(Math.random()*9+2)//將div放置到body中document.body.appendChild(div) } //獲取元素 var box = document.getElementsByClassName( 'ball' ) //獲取文檔可視區(qū)域的寬高 var maxX = document.documentElement.clientWidth - box[0].offsetWidth; var maxY = document.documentElement.clientHeight - box[0].offsetHeight; //自適應(yīng)窗口 window.onresize = function(){maxX = document.documentElement.clientWidth - box[0].offsetWidth;maxY = document.documentElement.clientHeight - box[0].offsetHeight; } play() function play(){for(var i=0;i<num;i++){ //獲取 var ball = box[i]; var startTop = ball.offsetTop; var startLift = ball.offsetLeft; //startTop都為零; var top = startTop + ball.speedY; var left = startLift + ball.speedX; //判斷小球是否出左右邊界 if(left <= 0 || left >= maxX){ //改變方向 ball.speedX = -ball.speedX; ball.style.background=randomColor() //判斷 if(left <= 0){ left = 0; }else if(left >= maxX){ left = maxX; } } //判斷小球是否出上下邊界 if(top <= 0 || top >= maxY ){ // 改變方向; ball.speedY = -ball.speedY; ball.style.background=randomColor() //判斷 if( top <= 0 ){ top = 0; }else if( top >= maxY ){ top = maxY; } } ball.style.top = top + 'px'; ball.style.left = left + 'px'; }//執(zhí)行動(dòng)畫幀requestAnimationFrame(play); } //顏色隨機(jī) function randomColor() {var r = Math.floor(Math.random() * 256), g = Math.floor(Math.random() * 256), b = Math.floor(Math.random() * 256); return 'rgb(' + r + ',' + g + ',' + b + ')'; } } </script></body></html>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法2. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析3. 淺談python出錯(cuò)時(shí)traceback的解讀4. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法5. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼6. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解7. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題8. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向9. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解10. Nginx+php配置文件及原理解析
