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

如何精简JavaScript代码仅保留按钮点击交互功能

代码精简方案

精简思路

你原代码中90%以上的逻辑都是处理YouTube播放器加载、封面切换的功能,和你需要的按钮点击渐隐交互完全无关,直接删除这部分冗余代码,只保留按钮交互核心逻辑即可。

精简后完整代码

JavaScript代码

document.addEventListener('DOMContentLoaded', function () {
  const body = document.body;
  // 监听渐隐动画结束,重置状态
  function animationEndHandler(evt) {
    if (evt.animationName === "fadeOutBody") {
      body.classList.remove("fadingOut");
    }
  }
  // 按钮点击触发渐隐效果
  function exitClickHandler() {
    body.classList.add("fadingOut");
  }
  // 给所有exit按钮绑定点击事件
  document.querySelectorAll(".exit").forEach(btn => {
    btn.addEventListener("click", exitClickHandler);
  });
  // 绑定动画结束监听
  body.addEventListener("animationend", animationEndHandler);
});

CSS代码(和原代码一致,无需修改)

.exit {
  top: auto;
  bottom: -47.63px;
  margin: auto;
  right: 0;
  left: 0;
  width: 47.63px;
  height: 47.63px;
  cursor: pointer;
  border: none;
  background: none;
  padding: 0;
  border-radius: 50%;
  animation: fadeInExit 0s forwards 0s;
  opacity: 0;
  pointer-events: none;
  clip-path: circle(50%);
}

@keyframes fadeInExit {
  99% {
    pointer-events: none;
  }

  100% {
    pointer-events: initial;
    opacity: 1;
  }
}

.exit svg {
  fill: red;
  transition: fill 3s ease;
}

.exit:hover svg,
.fadingOut .exit svg  {
  fill: green;
}

.fadingOut .exit {
  animation: fadeOutExit 8s forwards;
  pointer-events: none;
  opacity: 1;

}

@keyframes fadeOutExit {
  to {
    opacity: 0;
  }
}

HTML代码(和原代码一致,无需修改)

<button class="exit" type="button" aria-label="Close">
  <svg width="100%" height="100%" viewBox="-144 -144 288 288">
    <g id="exit">
      <title>exit</title>
      <path class="ex" fill="red" d="m-101.116-101.116a143 143 0 11202.232 202.232a143 143 0 01-202.232-202.232zzzz" />
      <circle cx="0" cy="0" r="113" />
      <path class="ex" fill="blue" d="m-101.116-101.116m169.705 11.313a113 113 0 00-137.178 0l68.589 68.59zm-158.392 21.214a113 113 0 000 137.178l68.59-68.589zm21.214 158.392a113 113 0 00137.178 0l-68.589-68.59zm158.392-21.214a113 113 0 000-137.178l-68.59 68.589z" />
    </g>
  </svg>
</button>

<button class="exit" type="button" aria-label="Close">
  <svg width="100%" height="100%" viewBox="-144 -144 288 288">
    <use href="#exit" />
  </svg>
</button>

<button class="exit" type="button" aria-label="Close">
  <svg width="100%" height="100%" viewBox="-144 -144 288 288">
    <use href="#exit" />
  </svg>
</button>
<button class="exit" type="button" aria-label="Close">
  <svg width="100%" height="100%" viewBox="-144 -144 288 288">
    <use href="#exit" />
  </svg>
</button>

精简效果

原JS代码近300行,精简后仅10余行,完全保留按钮点击变色、8秒渐隐的交互效果,没有冗余功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:24:00