js面向对象编程之选项卡案例

责编:menVScode 2017-06-17 0:02 阅读(908)

       html和css部分

<style>
	#box div{ width:200px; height:200px; border:1px #000 solid; display:none;}
	.active{ background:blue;}
</style>
<body>
	<div id="box">
	    <input class="active" type="button" value="1">
	    <input type="button" value="2">
	    <input type="button" value="3">
	    <div style="display:block">men</div>
	    <div>VS</div>
	    <div>code</div>
	</div>
</body>

        传统的过程式:

var oBox = document.getElementById('box');
var aInp = oBox.getElementsByTagName('input');
var aDiv = oBox.getElementsByTagName('div');
for (var i = 0; i < aInp.length; i++) {
	aInp[i].index = i;
	aInp[i].onclick = function(){
		for (var i = 0; i < aDiv.length; i++) {
			aInp[i].className = '';
			aDiv[i].style.display = 'none';
		};
		this.className = 'active';
		aDiv[this.index].style.display = 'block';
	}
};

        面向对象的方式:

window.onload = function(){
	var tabcase = new Tab('box');
	tabcase.autoPlay();
	tabcase.overOut();
};
function Tab(uid){
	this.oBox = document.getElementById(uid);
	this.aInp = this.oBox.getElementsByTagName('input');
	this.aDiv = this.oBox.getElementsByTagName('div');
	this.iNow = 0;
	this.timer = null;
	var _this = this;
	for (var i = 0; i < this.aInp.length; i++) {
		this.aInp[i].index = i;
		this.aInp[i].onclick = function(){
			_this.change(this);
		}
	}
}
//点击切换
Tab.prototype.change = function(oInp){
	for (var i = 0; i < this.aDiv.length; i++) {
		this.aInp[i].className = '';
		this.aDiv[i].style.display = 'none';
	};
	oInp.className = 'active';
	this.aDiv[oInp.index].style.display = 'block';
}	
//自动切换
Tab.prototype.autoPlay = function(){
	var _this = this;
	_this.timer=setInterval(function(){
		if(_this.iNow==_this.aInp.length-1){
			_this.iNow=0;
		}else{
			_this.iNow++;
		}
		
		for (var i = 0; i < _this.aDiv.length; i++) {
			_this.aInp[i].className = '';
			_this.aDiv[i].style.display = 'none';
		};
		_this.aInp[_this.iNow].className = 'active';
		_this.aDiv[_this.iNow].style.display = 'block';
	},2000);
}
//鼠标移入暂停,移出开始
Tab.prototype.overOut = function(){
	var _this = this; 
	this.oBox.onmouseover = function(){
		clearInterval(_this.timer);
	}
	this.oBox.onmouseout = function(){
		clearInterval(_this.timer);
		_this.autoPlay();
	}
}

改写成面向对象的过程要注意几点:

       1、全局的变量就是对象的属性;

       2、函数的就是对象的方法;

       3、一定要特别留意内部this指向问题:当有事件或者定时其存在时候,this指向会发生变化,尽量让面向对象中的this指向对象。

前端交流群: MVC前端网(menvscode.com)-qq交流群:551903636

邮箱快速注册

忘记密码