首頁  >  文章  >  web前端  >  在javascript+css3中如何實現打氣球小遊戲

在javascript+css3中如何實現打氣球小遊戲

亚连
亚连原創
2018-06-23 17:03:031696瀏覽

這是一個簡單但是印象深刻的小遊戲,打氣球小遊戲的實現代碼,主要基於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(&#39;body&#39;); //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(&#39;p&#39;); //用js生成标签
      balloon.className=&#39;balloon&#39;; //给创建的p元素设置类名
      balloon.style.left=randomL+&#39;px&#39;; //改变元素的样式中的left的值
      balloon.style.top=wH+&#39;px&#39;;
      balloon.speed=Math.random()*5+1; //自定义属性 创建元素的时候添加
      oBody.appendChild(balloon); //body中添加 元素对象
    }
  }
  timer=setInterval(function(){
    var oBall=document.querySelectorAll(&#39;.balloon&#39;);//获取页面所有的气球
    for(var i=0,len=oBall.length;i<len;i++){
      oBall[i].style.top = oBall[i].offsetTop-oBall[i].speed+&#39;px&#39;;
      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+&#39;px&#39;; //加速逃离
      ele.style.width=ele.offsetWidth-10+&#39;px&#39;; //宽度减少
      ele.style.height=ele.offsetHeight-10+&#39;px&#39;; //高度减少
    },30)
  }
</script>

上面是我整理給大家的,希望未來會對大家有幫助。

相關文章:

在zTree如何實作互動標籤

詳細講解EasyUI中abs的使用

#在EasyUI中如何使用accordion

#

以上是在javascript+css3中如何實現打氣球小遊戲的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn