Tab切换 原生JS方法
html静态样式:
<body>
<div id="tab">
<!-- 选项卡 -->
<div>
<ul class="tab_qie">
<li class="active">首页</li>
<li>添加列表</li>
<li>表格展示</li>
</ul>
</div>
<!-- 页面 -->
<div class="tab_box">
<!-- 1 -->
<div>
<h1>这是首页显示</h1>
</div>
<!-- 2 -->
<div class="hide">
<h1>添加列表</h1>
<form action="">
<span>姓名:</span>
<input type="text" name="" id="user">
<span>年龄:</span>
<input type="text" name="" id="age">
</form>
</div>
<!-- 3 -->
<div class="hide">
<h1>表格展示</h1>
<table border="1" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>id</td>
<td>小黑</td>
<td>22</td>
<td>
<button onclick="del()">删除</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
CSS样式:
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
.tab_qie {
width: 200px;
height: 600px;
line-height: 30px;
text-align: center;
background-color: gainsboro;
float: left;
}
.tab_qie .active {
color: white;
background-color: orange;
}
.tab_qie li:hover {
color: white;
background-color: orange;
}
.tab_qie li {
background-color: greenyellow;
border-bottom: 1px dashed gray;
}
.tab_box {
height: 600px;
float: left;
margin-left: 20px;
}
.tab_box .hide {
display: none;
}
table {
width: 80vh;
text-align: center;
}
</style>
jquery代码样式:
<script>
window.onload = function() {
// 获取dom元素
var Tab = document.getElementById('tab');
var Lis = Tab.getElementsByTagName('li');
var divOne = Tab.getElementsByTagName('div')[1];
var adiv = divOne.getElementsByTagName('div');
for (var i = 0; i < Lis.length; i++) {
Lis[i].index = i;
Lis[i].onclick = function() {
for (var j = 0; j < Lis.length; j++) {
Lis[j].className = ''; // 取消菜单样式
adiv[j].className = 'hide'; // 隐藏所有的tabDiv
}
Lis[this.index].className = 'active';
adiv[this.index].className = '';
}
}
}
</script>