ES6-面向对象实现tab切换

用面向对象的方式实现的简单tab切换功能 代码可以复用,第二个实现了简单的自动切换加了个定时器


<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>ES6-tab</title>
	<link rel="stylesheet" href="">
	<style>
		.on {background: #f60;color:#fff;}
		.box div{display: none;
			border: 1px solid #000;
			width: 200px;
			height: 200px;
		}
	</style>
</head>
<body>
	<div class="box" id="box">
		<input type="button" class="on" value="aaa">
		<input type="button" value="bbb">
		<input type="button" value="ccc">
		<div style="display: block">111</div>
		<div>222</div>
		<div>333</div>
	</div>
	<div class="box" id="box2">
		<input type="button" class="on" value="aaa">
		<input type="button" value="bbb">
		<input type="button" value="ccc">
		<div style="display: block">111</div>
		<div>222</div>
		<div>333</div>
	</div>
	<script>

		class Tab{
			constructor(id){
				this.oBox = document.getElementById(id);
				this.aBtn = this.oBox.getElementsByTagName("input");
				this.aDiv = this.oBox.getElementsByTagName("div");
				this.init();
				this.iNo = 0;
			}
			init(){
				for(let i=0;i<this.aBtn.length;i++){
					this.aBtn[i].οnclick=function(){
						this.hide();
						this.show(i);
					}.bind(this)
				}
			}
			hide(){
				for (let i = 0; i < this.aBtn.length; i++) {
					this.aBtn[i].className="";
					this.aDiv[i].style.display="none";
				}
			}
			show(index){
				this.aBtn[index].className="on";
				this.aDiv[index].style.display="block"
			}
		};

		window.οnlοad=function(){
			new Tab('box');
			new AutoTab('box2');
		}
		class AutoTab extends Tab{
			constructor(id){
				super(id);
				setInterval(this.next.bind(this),1000)
			}
			next(){
				this.iNo++;
				console.log("123")
				if(this.iNo == this.aBtn.length){
					this.iNo = 0;	
				}
				this.hide();
				this.show(this.iNo)
			}
		}
	</script>
</body>
</html>


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值