JavaScript写选项卡

时间:2023-10-26 13:30:25

方法一:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选项卡1</title>
<style>
#div1 div {
width: 200px;
height: 200px;
background-color: #ccc;
border: 1px solid pink;
display: none; //默认不显示DIV
} #div1 .active {
background-color: greenyellow;
}
</style>
<script>
window.onload = function () {
var oDiv = document.getElementById('div1');
var aBtn = oDiv.getElementsByTagName('input');
var aDiv = oDiv.getElementsByTagName('div'); for(i=0;i<aBtn.length;i++){
aBtn[i].index = i; //给按钮自定义一个index属性,用于改变DIV
aBtn[i].onclick = function () {
for(i=0;i<aBtn.length;i++){
aBtn[i].className = ''; //点击当前按钮时,取消对上一个按钮的设置
aDiv[i].style.display = 'none'; //点击当前按钮时,取消对上一个按钮对应的DIV的设置
}
this.className = 'active'; //点击按钮时,背景颜色改变
aDiv[this.index].style.display = 'block';
}
} }
</script>
</head>
<body>
<div id="div1">
<input class="active" type="button" value="教育"/>
<input type="button" value="培训"/>
<input type="button" value="招生"/>
<input type="button" value="出国"/>
<div style="display: block;">1234</div>
<div>2345</div>
<div>3456</div>
<div>4567</div>
</div>
</body>
</html>

方法二:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>选项卡2</title> <style> #div1 div{height:200px; width:200px; border:1px solid purple}
#div1 .active{background-color: olivedrab;}
</style>
<script>
window.onload = function () {
var arr = [1234,"abcd","fsafa","fabf"]; //以数组的方式列出Div里面的内容
var aDiv = document.getElementById('div1');
var aBtn = aDiv.getElementsByTagName('input');
var oDiv = aDiv.getElementsByTagName('div')[0]; //获取选项卡内容区域第一个Div for (var i = 0; i < aBtn.length; i++) {
aBtn[i].index = i; //给Div自定义的一个索引属性
aBtn[i].onclick = function () {
for (var i = 0; i < aBtn.length; i++) {
aBtn[i].className = ''; //清空上一步选项卡标签项的设置
}
this.className = 'active'; //点击时启用active类属性设置
oDiv.innerHTML = arr[this.index]; //将数组元素赋给Div
oDiv.style.display = 'block'; //显示Div内容
}
}
}
</script>
</head>
<body>
<div id="div1">
<input class="active" type="button" value="教育"/>
<input type="button" value="培训"/>
<input type="button" value="招生"/>
<input type="button" value="出国"/>
<br/><br/>
<div style="display: block;">1234</div> </div>
</body>
</html>