使用jq实现tab切换,效果如下
完整代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>tab切换</title> <style type="text/css"> #box{ height: 400px; width: 600px; border: 1px solid #ccc; padding: 10px; } ul{ height: 30px; width: 600px; padding: 0; margin: 0; } li{ display: block; text-align: center; width: 100px; float: left; list-style: none; cursor: pointer; height: 30px; line-height: 30px; } .choice{ background: #409EFF; color: #fff; } .tab-item{ display: none; } .show{ display: block; } </style> </head> <body> <ul> <li tabid="1" class="choice">tab1</li> <li tabid="2">tab2</li> <li tabid="3">tab3</li> </ul> <div id="box"> <div class="tab-item show">Tab-item1</div> <div class="tab-item">Tab-item2</div> <div class="tab-item">Tab-item3</div> </div> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script type="text/javascript"> $("li").click(function(){ // 修改tab标签样式 $(this).attr("class","choice") $(this).siblings().attr("class","") // 获取tab ID var itemId = $(this).attr("tabid")-1; // 切换到指定tab $("#box").find("div:eq("+itemId+")").attr("class","show") $("#box").find("div:eq("+itemId+")").siblings().attr("class","tab-item") }) </script> </body> </html>