面向对象分析 OOA;
1. 创建元素.放入页面;
2. 设置随机位置; 有边界的;
3. 设置随机的目标;
4. 运动;
5. 运动结束之后,需要重新设置随机目标,重新进行运动.....
HTML布局
<div class="container"></div>
CSS样式
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.container {
width: 500px;
height: 300px;
background: #000;
position: relative;
margin: 100px auto;
}
.fire-bug {
width: 8px;
height: 8px;
position: absolute;
background: lightyellow;
border-radius: 50%;
animation: fireBug 3s infinite;
}
@keyframes fireBug{
0% {opacity: 1;}
50% {opacity: 0.2;}
100% {opacity: 1;}
}
</style>
js
<script src="../运动/animate.js"></script>
<script type="text/javascript">
// 创建元素,放入页面 设置随机位置有边界 运动 运动结束后,需要重新设置目标,重新进行运动
function Glowworm(selector){
//选择元素
this.container = document.querySelector(selector);
this.init();
}
Glowworm.prototype = {
constructor: Glowworm,
init : function(){
//创建
this.ele = this.creatEle();
//获取随机位置
var boundary = this.setBoundary();
this.ele.style.left = boundary.left + "px";
this.ele.style.top = boundary.top + "px";
//调用运动函数
animate(this.ele,this.setBoundary(),function(){
animate(this.ele,this.setBoundary(),arguments.callee.bind(this))
}.bind(this))
},
//创建元素
creatEle : function(){
var ele = document.createElement("div");
ele.className = "fire-bug";
this.container.appendChild(ele);
return ele;
},
//设置随机位置有边界
setBoundary : function(){
//边界
left_max = this.container.offsetWidth - this.ele.offsetWidth;
top_max = this.container.offsetHeight - this.ele.offsetHeight;
console.log(left_max,top_max)
return {
left : parseInt(Math.random() * left_max + 1),
top : parseInt(Math.random() * top_max + 1),
}
}
}
for(var i = 0; i < 30; i++){
new Glowworm(".container");
}
</script>
运动函数animate封装
function animate(ele,attr_options,callback){
//获取当前元素的属性
for(var attr in attr_options){
/*
记录属性、目标点、当前位置
{
"height":{
target : 200,
iNow : 元素当前属性值
}
}
*/
attr_options[attr] = {
target : attr === "opacity" ? attr_options[attr] * 100 : attr_options[attr],
iNow : attr === "opacity" ? parseInt(getComputedStyle(ele)[attr] * 100) : parseInt(getComputedStyle(ele)[attr])
}
}
//先关后开定时器
clearInterval(ele.timer);
ele.timer = setInterval(function(){
//1、获取速度 属性
for(var attr in attr_options){
//attr_options = {"height":{target : 200,iNow : 元素当前属性值}}
var item = attr_options[attr];
//目标
var target = item.target;
//起点
var iNow = item.iNow;
//缓冲速度的计算
var speed = (target - iNow) / 10;
//速度取整
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
//终止条件
if(Math.abs(target - iNow) <= Math.abs(speed)){
ele.style[attr] = attr === "opacity" ? target / 10 : target + "px";
//如果有多条属性同时运动,目标不一致的话,这个终止条件就不靠谱了,所以得重新找条件判断
//一条运动完成删除对象里面的数据
delete attr_options[attr];
//如果对象没有属性了,那么我们就可以关闭定时器了
for(var num in attr_options){
return false;
}
clearInterval(ele.timer);
typeof callback === "function" ? callback() : "";
}else{
//iNow放在定时器里面,值是动态改变的,所以得动态操作
attr_options[attr].iNow += speed;
ele.style[attr] = attr === "opacity" ? attr_options[attr].iNow / 100 : attr_options[attr].iNow + "px";
}
}
},30)
}