偶然浏览到imooc视频,以为课程安排的挺好的,选择《js课程Tab选项卡切换效果》,听了两遍课,写了3遍代码,对js和css的理解更加深入了。主要技术点:css定位position,js的定时器,修改css样式。 效果:javascript
<!doctype html> <html> <head> <meta charset="utf-8" /> <link href="style.css" rel="stylesheet" type="text/css" /> <script src="click.js" type="text/javascript"></script> </head> <body> <div id="main" class="main"> <div id="main-tit" class="main-tit"> <ul> <li class="selected">标签_1</li> <li>标签_2</li> <li>标签_3</li> <li>标签_4</li> <li>标签_5</li> </ul> </div> </div> </body> </html>
css:css
1 *{ 2 margin: 0px;padding:0px;list-style: none;font-size: 12px; 3 } 4 5 .main{ 6 width: 298px; 7 height: 98px; 8 border: 1px solid #eee; 9 margin: 30px; 10 background-color: white; 11 } 12 .main-tit 13 { 14 height: 27px; 15 position: relative; 16 } 17 /*ul是absolute定位的*/ 18 .main-tit ul 19 { 20 width: 300px; 21 position: absolute; 22 left: -1px; 23 } 24 /*21行,绝对定位,让ul相对于外面的盒子向左移1px,让li的边框可以和main-tit的边框重合*/ 25 .main-tit ul li 26 { 27 float: left; 28 height: 26px; 29 line-height: 26px; 30 text-align: center; 31 width: 58px; 32 padding:0px 1px; 33 border-bottom: 1px solid #eee; 34 } 35 36 .main-tit ul li.selected 37 { 38 padding:0px; 39 border-left:1px solid #eee; 40 border-right: 1px solid #eee; 41 border-bottom-color:white; 42 }
绝对定位的盒子以它的“最近”的一个已经定位的祖先元素为基准进行偏移。对它后面的盒子就好像这个盒子部存在同样
已经定位的含义,position属性被设置,而且不是static。html
js,这段js代码加入了随机初始化的代码。这样用户在登录标签的时候每次看的标签页内容就能够不同了。java
function $(id) { return typeof id==="string"?document.getElementById(id):id; } window.onload = tab; var index = 0; function tab() { var tits = $("main-tit").getElementsByTagName("li"); //alert(tits.length); var begin = GetRandomNum(0,tits.length-1); setSelect(begin); var timer = setInterval(autoplay,1000); for(var i=0;i<tits.length;i++) { tits[i].id=i; tits[i].onmouseover=function() { if(timer) { clearTimeout(timer); timer=null; } setSelect(parseInt(this.id)); } tits[i].onmouseout = function() { timer = setInterval(autoplay,1000); } } function autoplay() { setSelect(index); } function setSelect (curIndex){ for(var i=0;i<tits.length;i++) { tits[i].className=""; } tits[curIndex].className="selected"; console.log(index); index = curIndex+1; if(index>=tits.length) { index =0; } } function GetRandomNum(Min,Max) { var Range = Max - Min; var Rand = Math.random(); return(Min + Math.round(Rand * Range)); } }