html结构:css
<input type="button" class="yellow" value="按钮1">
<input type="button" value="按钮2" class="">
<input type="button" value="按钮3" class="">
<div style="display: block;">内容1</div>
<div style="display: none;">内容2</div>
<div style="display: none;">内容3</div>
复制代码
css样式:html
div {
width: 200px;
height: 200px;
background: red;
display: none;
}
.yellow {
background: yellow;
}
复制代码
js交互逻辑:bash
//面向对象选项卡 ES5
function myTab(){
this.inputs=document.querySelectorAll('input');
this.divs=document.querySelectorAll('div');
};
myTab.prototype.init=function(){
var that=this;
for(var i=0;i<this.inputs.length;i++){
this.inputs[i].index=i;
this.inputs[i].onclick=function(){
for(var i=0;i<that.inputs.length;i++){
that.inputs[i].className='';
that.divs[i].style.display='none';
}
this.className='yellow';
that.divs[this.index].style.display='block';
}
}
};
var d=new myTab();
d.init();
//ES5结束
//面向对象选项卡 ES6 class类
class myTab{
constructor(){
this.inputs=document.querySelectorAll('input');
this.divs=document.querySelectorAll('div');
};
init(){
var that=this;
for(var i=0;i<this.inputs.length;i++){
this.inputs[i].index=i;
this.inputs[i].onclick=function(){
for(var i=0;i<that.inputs.length;i++){
that.inputs[i].className='';
that.divs[i].style.display='none';
}
this.className='yellow';
that.divs[this.index].style.display='block';
}
}
}
};
var d=new myTab();
d.init();
//ES6结束
//面向过程选项卡
var inputs=document.querySelectorAll('input');
var divs=document.querySelectorAll('div');
for(var i=0;i<inputs.length;i++){
inputs[i].index=i;
inputs[i].onclick=function(){
for(var i=0;i<inputs.length;i++){
inputs[i].className='';
divs[i].style.display='none';
}
this.className='yellow';
divs[this.index].style.display='block';
}
}
//jQ选项卡 简单操做
var inputs=$('input');
inputs.click(function(){
//this=>原生对象
//console.log(this);
inputs.removeClass('yellow');
$(this).addClass('yellow');
// index() 从一堆的元素中找到指定元素所处的位置
//console.log(inputs.index($(this)));
$('div').hide();
$('div').eq((inputs.index($(this)))).show();
});
//jQ选项卡 复杂操做,原生的思惟
$('input').each(function(index,item){
$('input')[index].setAttribute('id',index);
$(this).click(function(){
//全部的
$('input').each(function(index,item){
$('input').eq(index).removeClass('yellow');
$('div').eq(index).hide();
});
//当前的
$(this).addClass('yellow');
$('div').eq(index).show();
})
});
//data属性使用
$('input').each(function(index,item){
$(item).data('index',index);
$(item).click(function(){
var index=$(item).data('index');
$('input').removeClass('yellow')
$(this).addClass('yellow');
$('div').hide();
$('div').eq(index).show();
})
});
//用纯jQ的思惟写选项卡:
$('input').click(function(){
$('input').removeClass('yellow');
$(this).addClass('yellow');
$('div').hide();
//eq获取指定下标的jQ对象
$('div').eq(($('input').index($(this)))).show();
});
复制代码
写代码不是写代码的自己,而是把你的思惟方式表达出来!ide