js练习 左侧菜单栏

点击主菜单选项展开相应的子菜单,再次点击主菜单选项则相应的子菜单收回

<html>
<head>
<meta charset="utf-8">
<title>左侧菜单栏</title>
<style type="text/css">
    *{ margin:0 auto; padding:0;}
    #wai{ width:200px; height:600px; margin-top:50px;}
    .bt{ width:200px; height:30px; background-color:#06F; border:1px solid blue; border-top:none; text-align:center; line-height:30px; color:#fff;}
    .fbt{ width:200px; height:60px; display:none;}
    .zbt{ width:200px; height:30px; border:1px solid blue; border-top:none; text-align:center; line-height:30px; color:blue;}

</style>
</head>

<body>
    <div id="wai">
        <div class="bt"  xs="0" style="border-top:1px solid blue">电子产品</div>
        <div class="fbt">
            <div class="zbt">手机</div>
            <div class="zbt">电脑</div>
        </div>
        <div class="bt" xs="0">零食小吃</div>
        <div class="fbt">
            <div class="zbt">辣条</div>
            <div class="zbt">饼干</div>
        </div>
        <div class="bt" xs="0">洗化用品</div>
        <div class="fbt">
            <div class="zbt">洗衣液</div>
            <div class="zbt">洗衣粉</div>
        </div>
    </div>

</body>
</html>
<script type="text/javascript">
    var bt = document.getElementsByClassName("bt");
    /*
        用自定义的xs属性判断子菜单的状态,若子菜单隐藏则点击主菜单选项显示子菜单,若子菜单已显示,则点击主菜单选项收回子菜单
    */
    for(var i=0;i<bt.length;i++)
    {
        bt[i].onclick = function()
        {
            var xs = this.getAttribute("xs");
            if(xs==0)
            {
                this.nextSibling.nextSibling.style.display = "block";
                this.setAttribute("xs","1");
            }
            else
            {
                this.nextSibling.nextSibling.style.display = "none";
                this.setAttribute("xs","0");    
            }
        }
    }
     
</script>

效果   点击打开

原文地址:https://www.cnblogs.com/zxbs12345/p/8005475.html