JS 选项卡

ε祈祈猫儿з 提交于 2020-02-01 05:04:55
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .big{
            width:500px;
            height:400px;
            border:1px solid black;
            margin:auto;
        }
        .top{
            width:500px;
            height:50px;
            border-bottom: solid 1px black;
        }
        .top span{
            width:100px;
            height:50px;
            display: inline-block;
            text-align: center;
            line-height: 50px;
            float:left;
        }
        .active{
            background: red;
            color:white;
        }
        .bottom{
            width:498px;
            height:348px;
            position:relative;
        }
        .bottom div{
            width:100%;
            height:100%;
            position:absolute;
            left:0;
            top:0;
            font-size: 50px;
        }
        .bottom div:not(:first-of-type){
            display: none;
        }
    </style>
</head>
<body>
<div class="big">
    <div class="top">
     <span class="active">标题一</span>
     <span>标题二</span>
     <span>标题三</span>
     <span>标题四</span>
     <span>标题五</span>
    </div>
    <div class="bottom">
     <div>1</div>
     <div>2</div>
     <div>3</div>
     <div>4</div>
     <div>5</div>
    </div>
</div>
<script>
    var tops=document.getElementsByClassName("top")[0].children;
    var bottom=document.getElementsByClassName("bottom")[0].children;
    //方法一:索引属性赋值
//    for(var i=0;i<tops.length;i++){
//        tops[i].index=i;
//        tops[i].οnclick=function(){
//        //    方法一:
////            for(var k=0;k<tops.length;k++){
////                tops[k].className="";
////                bottom[k].style.display="none";
////            }
////            this.className="active";
////            bottom[this.index].style.display="block";
//
//            //    方法二:
//            for(var k=0;k<tops.length;k++){
//                if(tops[k].classList.contains("active")){
//                    tops[k].classList.remove("active");
//                    bottom[k].style.display="none";
//                }
//           }
//            this.classList.add("active");
//            bottom[this.index].style.display="block";
//        }
//    }
     //方法二:闭包
    for(var i=0;i<tops.length;i++) {
        (function (n) {
            var index=n;
            tops[index].onclick = function () {
                for (var k = 0; k < tops.length; k++) {
                    if (tops[k].classList.contains("active")) {
                        tops[k].classList.remove("active");
                        bottom[k].style.display = "none";
                    }
                }
                this.classList.add("active");
                bottom[index].style.display = "block";
            }
        })(i)
    }
</script>
</body>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!