利用jQuery实现一个简单Tab选项卡的切换,代码非常简洁。完整记录一下,以备日后使用。JS代码如下:
$(function () { $(".tabbox .menubox ul li").hover(function () { $(this).addClass("active").siblings().removeClass("active"); $(".tabbox .contentbox ul li").eq($(this).index()).show().siblings().hide(); }) })
完整代码如下,可以直接复制看看运行效果。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>jQuery实现Tab选项卡菜单</title> <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script> <style> * { margin: 0 auto; padding: 0; } .tabbox { width: 600px; margin-top: 20px; } .tabbox .menubox { width: 600px; height: 40px; border: none; } .tabbox .menubox ul {list-style: none;} .tabbox .menubox ul li { width: 200px; height: 40px; box-sizing: border-box; float: left; line-height: 40px; text-align: center; border: 1px solid #ccc; list-style: none; } .tabbox .menubox ul li.active { border-bottom: 0; } .tabbox .contentbox { width: 600px; height: 300px; box-sizing: border-box; border: 1px solid #ccc; text-align: center; border-top: none; } .tabbox .contentbox ul { list-style: none; } .tabbox .contentbox ul li { width: 600px; float: left; display: none; text-align: center; line-height: 200px; list-style: none; } .tabbox .contentbox ul li.selected { display: block; } </style> <script> $(function () { $(".tabbox .menubox ul li").hover(function () { $(this).addClass("active").siblings().removeClass("active"); $(".tabbox .contentbox ul li").eq($(this).index()).show().siblings().hide(); }) }) </script> </head> <body> <div class="tabbox"> <div class="menubox"> <ul> <li class="active">北京</li> <li>上海</li> <li>南京</li> </ul> </div> <div class="contentbox"> <ul> <li class="selected">北京北京北京北京</li> <li>上海上海上海上海</li> <li>南京南京南京南京</li> </ul> </div> </div> </body> </html>