如何使用CSS和 JavaScript在 Material Icons中实现菜单图标与关闭图标之间的切换动画?

前端开发 2026-07-11

我正在为我的网站创建一个导航切换按钮。点击按钮时,我希望在 menuclose 的Material Icons之间切换。图标通过JavaScript能正确切换,但切换过程是瞬间完成的,没有动画效果。如何在切换图标时添加平滑的动画效果?

<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<style>
#menuIcon{
  font-size:40px;
  cursor:pointer;
  transition: transform 0.3s ease;
}

.rotate{
  transform: rotate(180deg);
}
</style>
</head>

<body>

<span id="menuIcon" class="material-icons">menu</span>

<script>
const icon = document.getElementById("menuIcon");

icon.addEventListener("click", function() {
  if (this.textContent === "menu") {
    this.textContent = "close";
  } else {
    this.textContent = "menu";
  }

  this.classList.toggle("rotate");
});
</script>

</body>
</html>

解决方案

有多种方法可以为这个切换添加动画效果。你可以实现淡入淡出效果。

在CSS中:

.fade{
  opacity:0;
}

在JS中:

icon.addEventListener("click", function(){
  icon.classList.add("fade");
  if (this.textContent === "menu") {
    this.textContent = "close";
  } else {
    this.textContent = "menu";
  }
  icon.classList.toggle("rotate");
  setTimeout(() => {
    icon.textContent = icon.textContent === "menu" ? "close" : "menu";
    icon.classList.remove("fade");
  }, 150);

});
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章