You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SVG汉堡菜单的悬停动画改为点击切换动画?

实现点击切换的SVG汉堡菜单

要把悬停触发的动画改成点击切换,只需要两步:给菜单添加激活状态的CSS类,再用JS监听点击事件切换这个类。

步骤1:调整CSS样式

把原来的:hover伪类替换成自定义的.active类,只有当元素拥有这个类时,才会触发X样式的动画:

.hj {
  cursor: pointer;
}

.hamburg {
  display: flex;
  height: 100vh;
}

.hj,
.top,
.middle,
.bottom {
  transition: all 0.3s ease-in-out;
}

/* 替换hover为active类,用于点击触发 */
.hj.active .top {
  transform: rotate(45deg);
  transform-origin: center top;
  x: 37.5px;
  y: 26.25px;
}
.hj.active .middle {
  opacity: 0;
  x: 0;
}
.hj.active .bottom {
  transform: rotate(-45deg);
  transform-origin: center top;
  x: -15px;
  y: 18.75px;
}

步骤2:添加JS交互逻辑

给SVG元素绑定点击事件,每次点击切换.active类,实现汉堡和X样式的来回切换:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>点击切换汉堡菜单</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    .hj {
      cursor: pointer;
    }

    .hamburg {
      display: flex;
      height: 100vh;
    }

    .hj,
    .top,
    .middle,
    .bottom {
      transition: all 0.3s ease-in-out;
    }

    .hj.active .top {
      transform: rotate(45deg);
      transform-origin: center top;
      x: 37.5px;
      y: 26.25px;
    }
    .hj.active .middle {
      opacity: 0;
      x: 0;
    }
    .hj.active .bottom {
      transform: rotate(-45deg);
      transform-origin: center top;
      x: -15px;
      y: 18.75px;
    }
  </style>
</head>

<body>
  <div class="hamburg">
    <svg class="hj" height="75" width="75" viewBox="0 0 75 75">
            <rect class="top" x="15" y="21.75" width="45" height="5"></rect>
            <rect class="middle" x="15" y="34.1809" width="45" height="5"></rect> 
            <rect class="bottom" x="15" y="46.6117" width="45" height="5"></rect> 
        </svg>
  </div>

  <script>
    const hamburger = document.querySelector('.hj');
    hamburger.addEventListener('click', function() {
      this.classList.toggle('active');
    });
  </script>
</body>

</html>

修改完成后,第一次点击汉堡菜单会切换为X样式,再次点击就还原回原始汉堡样式,动画过渡效果和原来保持一致。

内容的提问来源于stack exchange,提问作者nickg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 12:00:20