JS面向對象實現選項卡
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1 input {
background: white;
}
#div1 input.active {
background: yellow;
}
#div1 div {
width: 200px;
height: 200px;
background: #ccc;
display: none;
}
</style>
<script>
window.onload = function() {
//創(chuàng)建一個選項卡對象,在某一個div中
new Tabswitch('div1');
}
function Tabswitch(id) {
var _this = this;
var oDiv = document.getElementById(id);
//定義選項卡的兩個屬性,分別為上面的選擇器和下面的顯示內容
this.aBtn = oDiv.getElementsByTagName('input');
this.aDiv = oDiv.getElementsByTagName('div');
//循環(huán)初始化選項卡的各個選擇按鈕
//初始化兩個地方,1是選項卡的index屬性,另一個為選項卡的方法
for(var i = 0; i < this.aBtn.length; i++) {
this.aBtn[i].index = i;
this.aBtn[i].onclick = function() {
_this.fnClick(this);
};
}
}
//統(tǒng)一定義點擊選項卡之后的方法
Tabswitch.prototype.fnClick = function(oBtn) {
// 將所有的選項卡狀態(tài)還原
for(var i = 0; i < this.aBtn.length; i++) {
this.aBtn[i].className = '';
this.aDiv[i].style.display = 'none';
}
//選擇,并操作
oBtn.classname = 'active';
this.aDiv[oBtn.index].style.display = 'block';
}
</script>
</head>
<body>
<div id="div1">
<input class="active" type="button" value="aaa" />
<input type="button" value="bbb" />
<input type="button" value="ccc" />
<div style="display: block;">aaa</div>
<div>afdafje</div>
<div>afjeiofje</div>
</div>
</body>
</html>
JS面向過程實現選項卡
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
#div1 input{
background: white;
}
#div1 input.active{
background: yellow;
}
#div1 div{
width: 200px;
height: 200px;
background: #ccc;
display: none;
}
</style>
<script>
window.onload = function(){
var oDiv = document.getElementById('div1');
var aBtn = oDiv.getElementsByTagName('input');
var aDiv = oDiv.getElementsByTagName('div');
for(var i = 0;i<aBtn.length;i++)
{
aBtn[i].index = i;
aBtn[i].onclick = function(){
for (var i=0;i<aBtn.length;i++) {
aBtn[i].className= '';
aDiv[i].style.display = 'none';
}
this.classname = 'active';
aDiv[this.index].style.display='block';
};
}
}
</script>
</head>
<body>
<div id="div1">
<input class="active" type="button" value="aaa" />
<input type="button" value="bbb" />
<input type="button" value="ccc" />
<div style="display: block;">aaa</div>
<div>afdafje</div>
<div>afjeiofje</div>
</div>
</body>
</html>
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者