其他分享
首页 > 其他分享> > 【js效果】竖向折叠二级菜单

【js效果】竖向折叠二级菜单

作者:互联网

效果图:

源码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>js实现竖向折叠二级菜单</title>
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
        font-size: 13px;
        list-style: none;
      }

      .menu {
        width: 210px;
        margin: 50px auto;
        border: 1px solid #ccc;
      }

      .menu p {
        height: 25px;
        line-height: 25px;
        font-weight: bold;
        background: #eee;
        border-bottom: 1px solid #ccc;
        cursor: pointer;
        padding-left: 5px;
      }

      .menu div ul {
        display: none;
      }

      .menu li {
        height: 24px;
        line-height: 24px;
        padding-left: 5px;
      }
    </style>
  </head>
  <body>
    <div class="menu" id="menu">
      <div>
        <p>Web前端</p>
        <ul style="display: block">
          <li>JavaScript</li>
          <li>DIV+CSS</li>
          <li>jQuery</li>
        </ul>
      </div>
      <div>
        <p>后台脚本</p>
        <ul>
          <li>PHP</li>
          <li>ASP.net</li>
          <li>JSP</li>
        </ul>
      </div>
      <div>
        <p>前端框架</p>
        <ul>
          <li>Extjs</li>
          <li>Esspress</li>
          <li>YUI</li>
        </ul>
      </div>
    </div>
    <script type="text/javascript">
      function $(id) {
        return document.getElementById(id);
      }
      window.onload = function () {
        // 将所有点击的标题和要显示隐藏的列表取出来
        var aDiv = $("menu").getElementsByTagName("div");
        var aUl = $("menu").getElementsByTagName("ul");
        var checkIndex = 0;
        // 遍历所有要点击的标题且给它们添加索引及绑定事件
        for (var i = 0; i < aDiv.length; i++) {
          aDiv[i].index = i;
          aDiv[i].onclick = function () {
            if (checkIndex == this.index) {
              if (aUl[this.index].style.display == "block") {
                aUl[this.index].style.display = "none";
                return;
              } else {
                aUl[this.index].style.display = "block";
                return;
              }
            }

            for (var j = 0; j < aUl.length; j++) {
              aUl[j].style.display = "none";
            }
            aUl[this.index].style.display = "block";
            checkIndex = this.index;
          };
        }
      };
    </script>
  </body>
</html>

标签:index,style,菜单,menu,aUl,js,竖向,var,display
来源: https://www.cnblogs.com/hellocd/p/14254877.html