原生js实现tab选项卡切换功能

代码2019-05-31433 人已阅来源:网络

原生js实现tab选项卡切换功能,具体效果可以点击运行代码进行预览。

运行代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>原生js实现tab选项卡切换功能 ——www.tonjay.com</title>
    <style>
    * {margin:0;padding:0;list-style:none;font-family:Arial,Helvetica,sans-serif;}
    .tabBox {border:1px solid #eee;max-width:600px;margin:30px auto;}
    ul {display:flex;text-align:center;width:100%;background:#fafafa;line-height:2.5;}
    li {flex:1;border-bottom:1px solid #eee;}
    li.active {background:#fff;border-bottom:none;color:darkcyan;}
    li:nth-child(n+2) {border-left:1px solid #eee;}
    .box {padding:30px;display:none;}
    </style>
</head>
<body>
    <div class="tabBox">
        <ul class="tab">
            <li>a</li>
            <li>b</li>
            <li>c</li>
            <li>d</li>
        </ul>
        <div class="content">
            <div class="box">tonjay.com</div>
            <div class="box">2</div>
            <div class="box">3</div>
            <div class="box">4</div>
        </div>
    </div>
    <script>
        window.onload = function(){
            var lis = document.getElementsByTagName("li");
            var boxs = document.getElementsByClassName("box");
            if(lis.length != boxs.length){
                console.log("注意,有错误")
                return;
            }
            lis[0].className='active';
            boxs[0].style.display='block';
            for(var i=0;i<lis.length;i++){
                lis[i].id = i;
                lis[i].onmouseover=function(){
                    for(var i=0;i<lis.length;i++){
                        lis[i].className = '';
                        boxs[i].style.display = 'none';
                    }
                    this.className = 'active';
                    boxs[this.id].style.display = 'block';
                }
            }
        }
    </script>
</body>
</html>