【原生JS】切换选项卡

 

效果图:

 

 

 

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <link rel="stylesheet" href="css/style.css" />
        <script src="js/script.js"></script>
    </head>
    <body>
        <div class="body">
            <div class="box" id="box">
                <ul class="title">
                    <a href="#"><li id="t1" onclick="oclick('t1')">新闻</li></a>
                    <a href="#"><li id="t2" onclick="oclick('t2')">杂志</li></a>
                    <a href="#"><li id="t3" onclick="oclick('t3')">动漫</li></a>
                    <a href="#"><li id="t4" onclick="oclick('t4')">音乐</li></a>
                </ul>
                <div id="d1" style="display: none">
                    THIS IS 1
                </div>
                <div id="d2" style="display: none">
                    THIS IS 2
                </div>
                <div id="d3" style="display: none">
                    THIS IS 3
                </div>
                <div id="d4" style="display: none">
                    THIS IS 4
                </div>
            </div>
        </div>
    </body>
</html>

 

CSS:

    *{padding: 0; margin: 0;}
    .box .title,.box .title li{padding:0;margin: 0;}
    .body{width: 1200px; height: 1000px; box-shadow: 0 0 5px gray; margin: 0 auto; border: 1px solid #808080;}
    .box{width: 420px; height: 266px;  box-shadow: 0 0 5px gray; margin: 200px auto; border: 1px solid #808080;}
    .box .title{list-style: none; text-align: center;}
    .box .title li{width:80px; height:40px; font:12px/40px "微软雅黑"; float:left; background:ghostwhite; border:1px solid #f2f2f2;}
    .box .title a li:hover{background:#F2F2F2}
    .box div{width:420px; height:220px; margin-top:46px;}
    

 

JS:

// This is Glunefish js function.
    function oclick(x){var obj = document.getElementById(x);
        obj.style.border='none';
        obj.style.background='#fff';
        var ttotal = ['t1','t2','t3','t4'];
        for(var i=0;i<4;i++){
            if(ttotal[i] == x){
                boxchange(i) ;
                ttotal.splice(i,1);
                continue;}
            }
        for(var i=0;i<ttotal.length;i++){
            var obj = document.getElementById(ttotal[i]);
            obj.style.border='1px solid #f2f2f2';
            obj.style.background='ghostwhite';}
        }
    function boxchange(x){
        var dlist = ['d1','d2','d3','d4'];
        for(var i=0;i<dlist.length;i++){
            document.getElementById(dlist[i]).style.display='none'}
            document.getElementById(dlist[x]).style.display='block';
    }
    onload = function(){oclick('t1');}

 

posted @ 2017-04-03 19:33  GruntFish  阅读(248)  评论(0编辑  收藏  举报