Html代码如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <title>选项卡</title> <link href="css/bootstrap.css" rel="stylesheet"> <style type="text/css"> *{ padding: 0; margin:0; } .content { padding:100px; } .ct-ul { list-style: none; display: flex; margin-bottom: 0; } .ct-ul li { padding: 5px 10px; margin-right: -1px; border: solid 1px #ccc; border-bottom: none; cursor: pointer; } .ct-list { border: solid 1px #ccc; margin-top: -1px; min-height: 100px; } .one { background-color: #fff; } </style> </head> <body> <div class="content"> <ul class="ct-ul"> <li class="ct-li one">选项一</li> <li class="ct-li">选项二</li> <li class="ct-li">选项三</li> <li class="ct-li">选项四</li> </ul> <div class="ct-list"> <div class="item">选项一内容</div> <div class="item">选项二内容</div> <div class="item">选项三内容</div> <div class="item">选项四内容</div> </div> </div> </body> </html>
Jquery代码如下
<script src="js/jquery-1.10.2.js"></script> <script> $(function(){ $(".item:gt(0)").hide();//选择item类0之后的元素隐藏,为0的这个元素显示 //主要逻辑就在于找到选项卡和内容框相对应的下标 $(".ct-li").unbind('click').click(function(){ var _index = $(this).index();//获取点击元素的下标 $(this).addClass("one") //给点击的元素添加类 .siblings().removeClass();//相邻元素隐藏类 $(".item").eq(_index).show() .siblings().hide();//选择item元素中第_index个显示出来,相邻元素被隐藏 }) }) </script>
效果图如下