js练手

公司项目的需要,这个效果并没有什么出彩的地方,只是比较满意里面的写法。

function luckyDraw(){this.init.apply(this,arguments)};
luckyDraw.prototype = {
	init:function(cons,prev,next){
		var _this = this;
		this.go = false;
		this.len = cons.length;
		this.cur = 0;
		next.onclick = function(){
			if(_this.go) return;
			_this.show(cons,1,_this.cur);
		}
		prev.onclick = function(){
			if(_this.go) return;
			_this.show(cons,-1,_this.cur);
		}
	},
	setAlpha:function(el,val){
		el.style.filter = "alpha(opacity=" + parseInt(val * 100) + ")";
        el.style.opacity = val;
	},
	show:function(node,n,m){
		this.animate(node[m],0);
		m = n>0 ? (m==this.len-1 ? 0 : ++m) : (n<0 ? ( m==0 ? this.len-1 : --m) : m);
		this.cur = m;
		this.setAlpha(node[m],0)
		this.animate(node[m],1);
	},
	animate:function(node,n){
		var i=0,m=1,_this = this,timer = null;
		timer = n==0 ? setInterval(function(){
			_this.go = true;
			m-=0.2
			if(m<=0){clearInterval(timer);_this.go = false;}
			_this.setAlpha(node,m);
		},16) : ( n== 1 ? setInterval(function(){
			_this.go = true;
			i+=0.2;
			if(i>=1){clearInterval(timer); _this.go = false;}
			_this.setAlpha(node,i);
		},16) : null);
	}
}
function getEleByClassName(tag,oClass,parent){
	parent = parent || document;
	var eles = [];
	var el = parent.getElementsByTagName(tag),i=0,len=el.length;
	for(;i<len;i++){
		if(hasClass(el[i],oClass)) eles.push(el[i]);
	}
	return eles;
}
function hasClass(node,oClass){
	var sClass = node.className;
	return (' ' + sClass + ' ').indexOf(' '+oClass+' ') != -1;
}
var prev = document.getElementById('prev'),next = document.getElementById('next'),box = document.getElementById('test');
var cons = getEleByClassName('div','con',box);
new luckyDraw(cons,prev,next);
HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
	#test { width:500px; height:300px; position:relative;}
	.con { position:absolute; top:0; left:0; width:500px; height:300px; background:#ddd; font-size:60px; line-height:300px; text-align:center; filter:alpha(opacity=0); opacity:0;}
	.con img {width:500px; height:300px; }
	.con1 { z-index:5;filter:alpha(opacity:100%); opacity:1;background:blue}
	.con2 { z-index:4; background:red}
	.con3 { z-index:3;background:green}
	.con4 { z-index:2;background:yellow}
	.con5 { z-index:1;background:#eee}
</style>
</head>
<body>
<div id="test">
	<div class="con con1">1</div>
    <div class="con con2">2</div>
    <div class="con con3">3</div>
    <div class="con con4">4</div>
    <div class="con con5">5</div>
</div>
<input name="" type="button" value="prev" id="prev" />
<input name="" type="button" value="next" id="next" />
<script type="text/javascript" src="luckyDraw.js"></script>
</body>
</html>

posted @ 2010-11-23 11:09  zjhsd2007  阅读(492)  评论(2编辑  收藏  举报