js实现选项卡切换

这里写图片描述

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>选项卡切换</title>
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        body{
            font-size: 14px;
            font-family: "微软雅黑";
            color: #666;
            margin: 30px;
        }

        ul{
            width: 328px;
            overflow: hidden;
            background: #ccc;
            }

        li{
            list-style: none;
            float: left;
            width: 80px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border: 1px solid transparent;
            border-bottom: none;
            cursor: pointer;
        }

        li.active{
            border: 1px solid #000;
            border-bottom: none;
            height: 30px;
            background: #ff0;
        }

        .contents{
            width: 306px;
            border: 1px solid #ccc;
            border-top: none;
            height: 160px;
            line-height: 30px;
            padding-left: 20px;
        }

        .contents div{display: none;}
    </style>
</head>
<body>
    <ul>
        <li class="active">选择1</li>
        <li>选择2</li>
        <li>选择3</li>
        <li>选择4</li>
    </ul>
    <div class="contents">
        <div style="display: block;">内容1</div>
        <div>内容2</div>
        <div>内容3</div>
        <div>内容4</div>
    </div>
</body>
<script type="text/javascript">
    window.onload=function(){
        //获取每个li
        var aLi = document.querySelectorAll('ul li');
        //获取每个div
        var aDiv = document.querySelectorAll('.contents div');
        // 为每个li元素添加鼠标经过的事件
        for(var i=0;i<aLi.length;i++){
            aLi[i].index = i;
            aLi[i].onmouseover = function(){
                 //鼠标经过时将每个li元素的样式设为空,div元素display为none
                for(var j=0;j<aLi.length;j++){
                    aLi[j].className="";
                    aDiv[j].style.display="none";
                }
                //当前li元素样式设为active,div元素display为block,每次鼠标进过都会执行这个脚本
                this.className ="active";
                aDiv[this.index].style.display = "block";
            }
        }
    }
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值