html代码
<div class="tabs"> <nav class="tab-title"> <a href="javascript:;" class="active" data-cont="toutiao">头条</a> <a href="javascript:;" data-cont="resou">热搜</a> <a href="javascript:;" data-cont="paihang">排行榜</a> <a href="javascript:;" data-cont="guonei">国内</a> </nav> <div class="tab-content"> <section class="cont" id="toutiao"> 头条 </section> <section class="cont" id="resou"> 热搜 </section> <section class="cont" id="paihang"> 排行榜 </section> <section class="cont" id="guonei"> 国内 </section> </div> </div>
CSS
html,body { margin:0; padding:0; width:100%; font-family:"Microsoft Yahei"; } .tabs { width:80%; height:300px; margin:50px 10%; border:1px solid #ccc; } .tab-title { display:flex; background:#fff; } .tab-title a { display:block; text-decoration:none; text-align:center; width:25%; height:40px; flex:1; padding:0 10px; color:#666; font-size:16px; line-height:40px; border-right:1px solid #f40; border-bottom:2px solid #f40; } .tab-title a:last-child { border-right:0; } .tab-title a.active { color:#f40; border-bottom:0; } .tab-content { width:100%; height:100%; } .tab-content .cont { display:none; overflow:hidden; font-size:50px; }
JS部分
$(function() { var secId = $('.active').get(0).dataset["cont"]; $("#" + secId).css('display', 'block'); $('.tab-title').on('click', 'a', function(e) { var cur = $(".active"); cur.removeClass("active"); var currentSec = cur.get(0).dataset["cont"]; $("#" + currentSec).css('display', 'none'); this.classList.add("active"); var secID = this.dataset["cont"]; $(this).offset().top; $("#" + secID).css('display', 'block'); }) })
最终效果: