只需要使用css完成Tab切换功能

来源:互联网 发布:mac下好用的命令行终端 编辑:程序博客网 时间:2024/06/06 00:47
        传统的Tab切换功能一般使用的是div+css+js实现的,而若是不依靠js,只凭借div+css可以实现这样的功能吗?答案其实是可以的,这其中的奥秘在于css3的伪类以及相邻选择器,下面是代码示例:
<!DOCTYPE HTML><html><head><title>Tab切换功能</title><meta http-equiv="content-type" content="text/html;charset=utf-8"><style type="text/css">/*css reset*/html, body, div, span, applet, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre,a, abbr, acronym, address, big, cite, code,del, dfn, em, img, ins, kbd, q, s, samp,small, strike, strong, sub, sup, tt, var,b, u, i, center,dl, dt, dd, ol, ul, li,fieldset, form, label, legend,table, caption, tbody, tfoot, thead, tr, th, td,article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary,time, mark, audio, video{margin:0; padding:0; outline:none; font-family:"Microsoft YaHei";}li{list-style:none;}a{text-decoration:none; border:0;}img,button{border:0;}table{border-collapse:collapse;}article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section{display:block;}html,body{width:100%; height:100%; overflow:auto;}/*Tab style*/#main{position:relative; width:96%; height:80%; margin:30px auto 0;}.radio{position:absolute; left:10px; top:40px; clear:both; z-index:-1;}.lab{position:relative; float:left; min-width:80px; height:30px; line-height:30px; padding:0 10px; margin-right:6px;border-top:3px solid #0878aa; color:#fff; font-size:13px; text-align:center; background-color:#0878aa; cursor:pointer; z-index:10;}.tbCont{position:absolute; left:0; top:33px; width:100%; min-height:calc(100% - 33px); border-bottom:3px solid #0878aa; background-color:#ececec; overflow:auto; z-index:10; clear:both; display:none;}.radio:checked + .lab{color:#0878aa; background-color:#ececec;}/*此处使用到了css3伪类以及相邻选择器*/.radio:checked + .lab + .tbCont{display:block;}/*此处使用到了css3伪类以及相邻选择器*/</style></head><body><div id="main"><input type="radio" id="sel1" name="sel" class="radio" checked="checked"/><label for="sel1" class="lab">首页</label><div class="tbCont">我是首页</div><input type="radio" id="sel2" name="sel" class="radio"/><label for="sel2" class="lab">页签1</label><div class="tbCont">内容1内容1内容1</div><input type="radio" id="sel3" name="sel" class="radio"/><label for="sel3" class="lab">页签2</label><div class="tbCont">内容2内容2内容2</div><input type="radio" id="sel4" name="sel" class="radio"/><label for="sel4" class="lab">页签3</label><div class="tbCont">内容3内容3内容3</div><input type="radio" id="sel5" name="sel" class="radio"/><label for="sel5" class="lab">页签4</label><div class="tbCont">内容4内容4内容4</div><input type="radio" id="sel6" name="sel" class="radio"/><label for="sel6" class="lab">页签5</label><div class="tbCont">内容5内容5内容5</div></div></body></html>
      测试过以上代码在各种主流浏览器的兼容性没有什么问题,除了IE8及以下(低版本的IE浏览器只能乖乖的用js实现了),总体来讲,能够使用css实现的功能就不要用js来实现,毕竟关系到性能效率等问题,如果大神们发现有什么问题或者有更好的提议也随时欢迎来一起讨论!

原创粉丝点击