简单、容易理解,适合jq初学者。保存html代码于本地,既可运行查看效果。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jquery极致简单的tab切换</title>
<style>
body{margin: auto;padding: 0;border: 0;outline: 0;font-size: 100%;vertical-align: baseline;background: transparent;}
ul,li{list-style: none;}
/*tab样式*/
.tab-container{position: relative;width: 500px;margin: 10px auto;}
.tab-container .tab-hd{position: relative;margin: 0;padding: 0;float: left;height: 33px;border-bottom: 1px solid #999;border-left: 1px solid #999;width: 100%;clear: both;}
.tab-container .tab-hd li{float: left;margin: 0;padding: 0 20px;height: 32px;line-height: 32px;font-size: 14px;border: 1px solid #999;border-left: none;margin-bottom: -1px;background: #e0e0e0;overflow: hidden;position: relative;cursor: pointer;}
.tab-container .tab-hd li.active{background: #fff;border-bottom: 1px solid #fff;}
.tab-container .tab-bd{position: relative;border: 1px solid #999;border-top: none;clear: both;float: left;width: 100%;background: #fff;}
.tab-container .tab-bd .tab-item{display: none;padding: 20px;font-size: 14px;}
.tab-container .tab-bd .tab-item.active{display: block;}
</style>
</head>
<body>
<div class="tab-container">
<ul class="tab-hd">
<li>tab1</li>
<li>tab2</li>
<li>tab3</li>
<li>tab4</li>
</ul>
<div class="tab-bd">
<div class="tab-item">container1</div>
<div class="tab-item">container2</div>
<div class="tab-item">container3</div>
<div class="tab-item">container4</div>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('.tab-container').each(function(index, el) {
var hd = $(el).find('.tab-hd li'); //菜单按钮层
var bd = $(el).find('.tab-bd .tab-item'); //切换内容层
//开始切换事件
hd.click(function(event) {
var cur = $(this).index(); //获取li相对位置
/*hd层事件*/
hd.removeClass('active'); //清掉所有li的"active"类
$(this).addClass('active'); //给点击的li添加"active"类
/*bd层事件*/
bd.removeClass('active');
bd.eq(cur).addClass('active');
}).first().click(); //默认第一次执行
});
});
</script>
</body>
</html>
#效果截图