前段时间写了个 tabs 选项卡切换效果,今天抽空在原有的基础上进行了扩展,加入了自动轮播,这样就变成了类似图片轮播的效果了。
html 代码:
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>js-tabs</title> <link rel="stylesheet" type="text/css" href="../css/base.css" media="all"/> <style type="text/css"> a{color:#a0b3d6;} .tabs{border:1px solid #a0b3d6;margin:100px;width:300px;} .tabs-nav a{background:#eaf0fd;line-height:30px;padding:0 20px;display:inline-block;border-right:1px solid #a0b3d6;border-bottom:1px solid #a0b3d6;float:left;} .tabs-nav .select1,.tabs-nav .select2,.tabs-nav .select3,.tabs-nav .select4{background:white;border-bottom:1px solid white;_position:relative;} .tabs-content{padding:20px;border-top:1px solid #a0b3d6;margin-top:-1px;} </style> </head> <body> <div class="tabs" id="tabs"> <h2 class="tabs-nav clearfix"> <a href="javascript:;">首页</a> <a href="javascript:;">技术</a> <a href="javascript:;">生活</a> <a href="javascript:;">作品</a> </h2> <p class="tabs-content">首页首页首页首页首页首页首页首页首页首页</p> <p class="tabs-content">技术技术技术技术技术技术技术技术技术技术</p> <p class="tabs-content">生活生活生活生活生活生活生活生活生活生活</p> <p class="tabs-content">作品作品作品作品作品作品作品作品作品作品</p> </div> <br/><br/> <div class="tabs" id="tabs2"> <h2 class="tabs-nav clearfix"> <a href="javascript:;">11111</a> <a href="javascript:;">22222</a> <a href="javascript:;">33333</a> </h2> <p class="tabs-content">11111111111111111111111111111111111</p> <p class="tabs-content ">222222222222222222222222222222222222</p> <p class="tabs-content ">333333333333333333333333333333333333333</p> </div> </body> </html> <script type="text/javascript" src="tabs.js"></script> <script type="text/javascript"> window.onload = function(){ tabs('tabs','click',true,1000); tabs('tabs2','mouseover'); } </script>
tabs.js 代码:
function tabs(id,trigger,autoplay,time){ var tabsWrap = document.getElementById(id); var tabsBtn = tabsWrap.getElementsByTagName('h2')[0].getElementsByTagName('a'); var tabsContent = getClass('tabs-content',tabsWrap); var timer = null; var current = 0; show(0); for(var i = 0,len = tabsBtn.length; i < len; i++){ tabsBtn[i].index = i; if(trigger == 'click'){ tabsBtn[i].onclick = function(){ show(this.index); } }else if(trigger == 'mouseover'){ tabsBtn[i].onmouseover = function(){ show(this.index); } } } if(autoplay){ autoPlay(); tabsWrap.onmouseover = function(){ clearInterval(timer); } tabsWrap.onmouseout = function(){ autoPlay(); } } function autoPlay(){ timer = setInterval(function(){ show(current); current++; if(current >= tabsBtn.length){ current = 0; } },time); } function show(n){ current = n; for(var i = 0,len = tabsBtn.length; i < len; i++){ tabsBtn[i].className = ''; tabsContent[i].style.display = 'none'; } tabsBtn[current].className = 'select' + (current + 1); tabsContent[current].style.display = 'block'; } function getClass(classname,obj){ var results = []; var elems = obj.getElementsByTagName('*'); for(var i = 0; i < elems.length; i++){ if(elems[i].className.indexOf(classname) != -1){ results[results.length] = elems[i]; } } return results; } }