折叠导航怎么设置?JavaScript实现折叠导航代码小案例

济南云服务器 2026年5月22日06:10:28JavaScript折叠导航怎么设置?JavaScript实现折叠导航代码小案例已关闭评论5阅读模式

为了方便用户更加快速的找到自己需要的内容,设计网站架构时,会增加多个类别,但是,如果将这些所有栏目同时呈现在页面中,很容易造成页面的混乱现象,不利于用户体验,遇到这种情况设计一个折叠导航,就是一个不错的解决方案,下面,济南网站建设news.hcsw666.com/小编就来为大家介绍一个通过编写JavaScript代码,设置折叠导航的小案例,有需要的朋友可以过来参考一下。

关键代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>

<title>JS折叠导航菜单</title>
<style>
  *{margin:0;padding:0;list-style:none;text-decoration:none;box-sizing:border-box;}
  body{background:#f5f5f5;}

  /* 导航容器 */
  .nav{
    width:220px;
    background:#2d374a;
    color:#fff;
    margin:30px;
  }

  /* 一级菜单 */
  .nav-item{
    border-bottom:1px solid #3b4455;
  }
  .nav-title{
    padding:14px 20px;
    cursor:pointer;
    font-size:15px;
    display:flex;
    justify-content:space-between;
    align-items:center;
  }
  .nav-title:hover{
    background:#374256;
  }

  /* 箭头 */
  .arrow{
    transition:transform 0.3s;
  }
  /* 展开时旋转箭头 */
  .nav-item.active .arrow{
    transform:rotate(180deg);
  }

  /* 二级菜单(默认折叠) */
  .sub-nav{
    height:0;
    overflow:hidden;
    transition:height 0.3s ease;
    background:#252d3d;
  }
  .sub-nav li a{
    display:block;
    padding:12px 30px;
    color:#ddd;
    font-size:14px;
  }
  .sub-nav li a:hover{
    background:#2f3a4e;
    color:#fff;
  }
</style>
</head>
<body>

<div class="nav">
  <div class="nav-item">
    <div class="nav-title">
      <span>网站建设</span>
      <span class="arrow">∨</span>
    </div>
    <ul class="sub-nav">
      <li><a href="#">企业官网</a></li>
      <li><a href="#">响应式网站</a></li>
      <li><a href="#">营销型网站</a></li>
    </ul>
  </div>

  <div class="nav-item">
    <div class="nav-title">
      <span>SEO优化</span>
      <span class="arrow">∨</span>
    </div>
    <ul class="sub-nav">
      <li><a href="#">关键词排名</a></li>
      <li><a href="#">站内优化</a></li>
      <li><a href="#">外链建设</a></li>
    </ul>
  </div>

  <div class="nav-item">
    <div class="nav-title">
      <span>案例展示</span>
      <span class="arrow">∨</span>
    </div>
    <ul class="sub-nav">
      <li><a href="#">济南企业案例</a></li>
      <li><a href="#">电商案例</a></li>
    </ul>
  </div>
</div>

<script>
  // 获取所有一级菜单
  const navItems = document.querySelectorAll('.nav-item');

  navItems.forEach(item => {
    const title = item.querySelector('.nav-title');
    const subNav = item.querySelector('.sub-nav');

    title.onclick = function(){
      // 判断当前是否展开
      const isOpen = item.classList.contains('active');

      // 先关闭所有
      navItems.forEach(i => {
        i.classList.remove('active');
        i.querySelector('.sub-nav').style.height = '0';
      });

      // 如果当前没展开,就展开
      if(!isOpen){
        item.classList.add('active');
        subNav.style.height = subNav.scrollHeight + 'px';
      }
    };
  });
</script>

</body>
</html>

济南云服务器
  • 本文由 发表于 2026年5月22日06:10:28
  • 转载请务必保留本文链接:http://news.hcsw666.com/2767