這篇文章主要介紹了關於javascript和css3開發打氣球小遊戲的完整代碼,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
這是一個簡單但是印象深刻的小遊戲,打氣球小遊戲的實現代碼,主要基於js和css3,基於css3畫氣球,具體實現代碼大家參考下本文
效果知識點:
css3畫氣球, 自訂屬性運用,隨機陣列, DOM元素操作,進階回呼函數與參數複傳,動態布局,滑鼠事件,定時器運用,CSS3新增樣式等。
css代碼如下:
<style>{margin:0;padding:0;}body{background:#434343;overflow:hidden}.balloon{position:absolute;left:0;top:0;margin:auto;width:160px;height:160px;圓角: 左上 右上 右下 左下 /css3旋轉 順時針旋轉45度 /background:#faf9f9;x軸的位置 y軸的位置 影子擴散程度 模糊度 顏色 /}.balloon:after{虛擬元素的內容 /display:block;position:absolute;
因為氣球是旋轉的 現在的正下方其實是右下角*/
right:0px;width:0px;height:0px;border:8px solid #dbbdbd;border-top-color:transparent;border-bottom-color:transparent;border-left-color:transparent;transform:rotate(45deg);border-radius:16px;}#wrap{width:200px;height:200px;background:red;}</style>
javascript代碼如下:
<script> var num = 10; // 聲明遍曆num 為p的數量 //var oBody = document.querySelector('body'); //h5 api 擷取元素的方法 var oBody=document.documentElement || document.body; //body擷取相容性寫法 var wW=window.innerWidth; //擷取瀏覽器視窗的寬度 var wH=window.innerHeight; //擷取瀏覽器視窗高度 var timer=null; //初始化定時器變數 init(num); function init(num){ for(var i=0;i<num;i++){ //for迴圈 迴圈加工廠 var randomL=Math.random()*wW; // 隨機left範圍 randomL=Math.min(wW-160,randomL); //規範left位置 var balloon = document.createElement('p'); //用js產生標籤 balloon.className='balloon'; //給建立的p元素設定類名 balloon.style.left=randomL+'px'; //改變元素的樣式中的left的值 balloon.style.top=wH+'px'; balloon.speed=Math.random()*5+1; //自訂屬性 建立元素的時候添加 oBody.appendChild(balloon); //body中添加 元素對象 } } timer=setInterval(function(){ var oBall=document.querySelectorAll('.balloon');//擷取頁面所有的氣球 for(var i=0,len=oBall.length;i<len;i++){ oBall[i].style.top = oBall[i].offsetTop-oBall[i].speed+'px'; oBall[i].onclick=function(){ //誰 觸發了什麼 誰做了什麼事情 crash(this,function(xxx){ clearInterval(xxx.timer); //清除動畫定時器 xxx.parentNode.removeChild(xxx); }); //this.parentNode.removeChild(this); init(1); } } },30); function crash(ele,cb){ //被點擊之後撒氣效果 ele.timeouter=setTimeout(function(){ cb&&cb(ele); },500) ele.timer=setInterval(function(){ ele.speed++; //加速度自增 ele.style.top=ele.offsetTop-ele.speed+'px'; //加速逃離 ele.style.width=ele.offsetWidth-10+'px'; //寬度減少 ele.style.height=ele.offsetHeight-10+'px'; //高度減少 },30) }</script>
以上就是本文的全部內容,希望對大家的學習有所協助,更多相關內容請關注topic.alibabacloud.com!