js tabバー切替原理

2115 ワード




    
    
    <style>
        .box {
            width: 400px;
            margin:100px auto;
            border:1px solid #ccc;
        }
        .bottom div{
            width:100%;
            height: 300px;
            background-color: pink;
            display: none;
        }
        .purple {
            background-color: purple;
        }
        .bottom .show {
            display: block;
        }

    </style>
    <script>
        window.onload = function(){
            var btns = document.getElementsByTagName("button");
            var divs = document.getElementById("divs").getElementsByTagName("div");
            for(var i= 0;i<btns.length;i++)
            {
                btns[i].index = i;  //  
                btns[i].onclick = function(){
                    //  btn  
                    //alert(this.index);
                    for(var j=0;j<btns.length;j++)
                    {
                        btns[j].className = "";
                        divs[j].className = "";
                    }
                    //      
                    this.className = "purple";
                    //  div 
                    //   
                    divs[this.index].className = "show";
                }
            }
        }
    </script>


<div class="box">
    <div class="top">
        <button> </button>
        <button> </button>
        <button> </button>
        <button> </button>
        <button> </button>
    </div>
    <div class="bottom" id="divs">
        <div class="show">1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
    </div>
</div>



</code></pre> 
 </div> 
</div>
                            </div>
                        </div>