JavaScript-选项卡

Posted on 2017-12-08 13:31  神笔码农  阅读(165)  评论(0编辑  收藏  举报
<style type="text/css">
*{ margin:0px auto; padding:0px;}
#wai{ width:100%; height:500px; margin-top:30px;}
#top{ width:100%; height:50px;}
#bottom{ width:100%; height:450px;}
.item{ width:100px; height:50px; float:left; text-align:center; vertical-align:middle; line-height:50px;}
.neirong{ width:100%; height:450px;}
#one{ background-color:red;}
#two{ background-color:green; display:none} /*设置2和3隐藏,让1为默认显示状态*/
#three{ background-color:blue; display:none}


</style>
</head>

<body>
    <div id="wai">
        <div id="top">
            <div class="item" style="background-color:red" guanlian="one">山东</div><!--设置此选项卡背景色为红色,表示默认为选中状态-->
            <div class="item" guanlian="two">淄博</div>
            <div class="item" guanlian="three">张店</div>
        </div>
        <div id="bottom">
            <div class="neirong" id="one"></div>
            <div class="neirong" id="two"></div>
            <div class="neirong" id="three"></div>
        </div>
    </div>
    
</body>
<script type="text/javascript">
    //给“item”添加点击事件:点击变红色,便是为选中状态
    var items = document.getElementsByClassName("item")
    for(var i=0;i<items.length;i++){
        items[i].onclick = function(){
            //让“item”恢复原色(白色)
            for(var i=0;i<items.length;i++){
            items[i].style.backgroundColor = "white";
            }
            //让被点击的“item”变为红色
            this.style.backgroundColor = "red";
            //让“item”与相应的1.2.3相关联:给“item”设置属性,分别对应1.2.3,提取出来
            var id = this.getAttribute("guanlian");
            var nr = document.getElementsByClassName("neirong");
            for(var i=0;i<nr.length;i++){
                //点击事件发生时让1.2.3全部隐藏,只让被点击的显示
                nr[i].style.display = "none";
            }
            document.getElementById(id).style.display = "block";
            
            
        }
            
    }
</script>