用css3画出气球形状

<style> *{padding:0;margin:0;} body{background: #222;overflow: hidden;} .balloon{ position: absolute; width: 160px; height: 160px; background: #faf9f9; border-radius: 160px 160px 64px 160px; transform: rotate(45deg); box-shadow: -8px -8px 80px -8px rgba(243,98,122,0.78) inset,36px 36px 24px rgba(243,98,122,0.28); } .balloon:after { position: absolute; display: block; content: ''; width: 0; height: 0; border: 8px solid transparent; border-right-color: rgba(243,98,122,0.88); background: transparent; transform: rotate(45deg); border-radius: 16px; bottom: -2px; right: -2px; } </style>

<script>

var ww = window.innerWidth; //获取浏览器窗口宽度 var wh = window.innerHeight; var bh = 160, bw = 160; //球的宽度高度 var num=10; var timer = null; init(num); move(); timer = setInterval(move,30);

//1、利用js动态生成div,并初始化气球坐标 function init(num) { for(var i=0;i<num;i++) { var randomX = Math.floor(Math.random()*ww)-bw; //防止气球超出右边 randomX = Math.abs(randomX); //防止气球超出左边 var balloons = document.createElement("div"); balloons.className = 'balloon'; balloons.style.top = wh-bh+'px'; balloons.style.left = randomX+'px'; balloons.speed = Math.random()*5+1; //气球上升随机速度 document.body.appendChild(balloons); } }

//2、让气球运动,并随机速度 function move() { //获取创建后的气球 var balloons = document.querySelectorAll('.balloon'); //遍历改变top值 var len=balloons.length; for(var i=0;i<len;++i) { (function(i) { //IIFE:匿名函数自执行 balloons[i].style.top = balloons[i].offsetTop-balloons[i].speed+'px'; balloons[i].onclick = function() { //延迟触发事件 boom.call(this,function() { clearInterval(this.timer); this.parentNode.removeChild(this);//移除元素自身 }.call(this)); //call:函数执行时刻改变this指向或者手动执行的时候 } })(i) } }

//3、点击气球,气球动画消失 function boom(cb) { this.timer = setInterval(function() { //定时器内部的this指向window if(this.offsetWidth<10) { cb&&cb(); //如果cb为真,则执行cb() } this.speed++; this.style.width = this.offsetWidth-10+'px'; this.style.height = this.offsetHeight-10+'px'; this.style.top = this.offsetTop-this.speed+'px'; }.bind(this),30) //bind:延迟触发的this绑定 }

一个不简单的气球动画

总结:难点主要是在点击气球让气球消失的函数涉及到this作用域的绑定。另本实例代码并非本人原创,供交流学习!