tab切换案例
做个简单的tab切换效果,分别于jquery和js操作
(1)jQuery操作
先看下效果:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> *{box-sizing:border-box;padding: 0;margin: 0} ul{width: 100%;height: 50px;text-align: center;margin: 10px 0;} ul li{list-style: none;height: 100%;width: 100px; line-height: 50px;text-align: center;background-color: #9c8b8b; margin: 0 6px;display: inline-block;cursor: pointer;} section{width: 600px;height: 300px;border: 1px solid red;margin: 100px auto;} #area{width: 400px;height: 200px;margin: 10px auto;border: 1px solid red;} .child{width: 100%;height: 100%;float: left;display: none;text-align: center;line-height: 200px;font-size: 20px;color: black;} .active{display: block} #area .child:nth-child(1){ background-color: red; } #area .child:nth-child(2){ background-color: green; } #area .child:nth-child(3){ background-color: blue; } #area .child:nth-child(4){ background-color: yellow; } </style> </head> <body> <section> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <div id="area"> <div class="child active"> 内容一 </div> <div class="child"> 内容二 </div> <div class="child"> 内容三 </div> <div class="child"> 内容四 </div> </div> </section> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> $(function(){ $("ul li").on('click',function(){ var index = $(this).index(); $(".child").each(function() { if (index == $(this).index()) { $(this).siblings().removeClass('active'); $(this).addClass('active'); } }) }) }) </script> </body> </html>
(2)js操作
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style> *{ padding: 0; margin: 0; } li{ list-style: none; float:left; } #tabCon { clear: both; } #tabCon div { display:none; } #tabCon div.fdiv { display:block; } </style> </head> <body> <div id="tanContainer"> <div id="tab"> <ul> <li>标题一</li> <li>标题二</li> <li>标题三</li> <li>标题四</li> </ul> </div> <div id="tabCon"> <div class="fdiv">内容一</div> <div>内容二</div> <div>内容三</div> <div>内容四</div> </div> </div> </body> <script> var tabs=document.getElementById("tab").getElementsByTagName("li"); var divs=document.getElementById("tabCon").getElementsByTagName("div"); for(var i=0;i<tabs.length;i++){ tabs[i].onclick=function(){ change(this); } } function change(obj){ for(var i=0;i<tabs.length;i++){ console.log(tabs[i]) if(tabs[i]==obj){ divs[i].className="fdiv"; }else{ divs[i].className=""; } } } </script> </html>
.