Tab選項卡切換效果,mooc教程

偶然瀏覽到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屬性被設置,而且不是statichtml

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));   
    }   
}
相關文章
相關標籤/搜索