`
cxy020
  • 浏览: 61096 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

js动画

阅读更多
最近写了一个动画效果。
例子中我只写了一个效果,增加高度,有兴趣的朋友可以自己在添加其他的效果。


function Animation(obj){
	this.ele = obj.ele;
	this.maxheight = obj.maxheight||26;
	this.minheight = obj.minheight||0;
	this.delay = obj.delay || 0;
	
	this.inter = null;
	this.time = obj.time||200;
	this.callback = obj.callback;
	this.type = obj.type || "addh";
	this.initialize.apply(this, arguments);
};

Animation.prototype={
	constructor:Animation,
	initialize:function(obj){
		this.events = [];//动画状态数组
		this.inittime = this.time;
	},
	start:function(){
		this.events.push(this.type);
		/*
		判断主循环 是否在执行 在执行的话就 只保存需要执行的状态  
		这样就可以保证一个dom只有一个 主循环 从而保证不会出现死循环
		*/
		if(this.inter == null){
			this.startAnimate();
		}
	},
	startAnimate:function(){
		this.time = this.inittime;
		var t = this;
		var type = t.events.pop();//获取最后一个动画
		t.events = [];
		//主循环
		t.inter = setInterval(function(){
			switch(type){
				case "addh":
					t.addh();
				break;
				case "delh":
					t.delh();
				break;
			}
		},50);
	},
	callBack:function(){
		var len = this.events.length;
		clearInterval(this.inter);
		var t = this;
		if(len == 0){
			this.inter = null;
			if(typeof this.callback == "function"){
				setTimeout(function(){
					t.callback();
				},this.delay);
			}
		}
		else{
			setTimeout(function(){
				t.startAnimate();
			},this.delay);
		}
	},
	addh:function(){
		var h = this.ele.height();
		var nh = Math.min(h+((this.time*this.time)/1000000)*10,this.maxheight);
		if(nh >= this.maxheight){
			this.callBack();
		}
		this.ele.height(nh);
		this.time += 1000;
	},
	delh:function(){
		var h = this.ele.height();
		var nh = Math.max(h-((this.time*this.time)/1000000)*10, this.minheight);
		if(nh <= this.minheight){
			this.callBack();
		}
		this.ele.height(nh);
		this.time += 1000;
	}
};


上面是基本代码
具体例子

<div style="border:1px solid red;width:100px;" id="div1"  >
<div style="border:1px solid green;width:50px;margin:auto;" id="div2" ></div>
</div>
<input type="button" value="同时动" id="btn1" />
<input type="button" value="分开动" id="btn2" />

<script type="text/javascript" >
$(function(){
	var div1 = new Animation({
		ele:$("#div1"),
		maxheight:200,
		minheight:0,
		delay:0
	});
	var div2 = new Animation({
		ele:$("#div2"),
		maxheight:100,
		minheight:0,
		delay:5000
	});
	
	$("#btn1").click(function(){
		div1.type="addh";
		div1.start();
		div2.type="addh";
		div2.start();
	});
	$("#btn2").click(function(){
		div1.type="addh";
		div1.start();
		div1.callback=function(){
			div2.type="addh";
			div2.start();
		};
	});
});
</script>


为了方便我在代码中 使用了jquery 。大家需要 引入jquery框架
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics