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

求助:CSS Transition仅第二次点击才生效,如何修复?

CSS Transition仅第二次点击生效的问题解决

问题核心原因

按钮的onclick="transitionEffect()"写法导致第一次点击只是执行了绑定点击事件的逻辑,并没有触发动画;第二次点击才会真正执行绑定的事件处理函数,所以过渡效果只在第二次点击时生效。

修正方案

1. 调整事件绑定时机

移除按钮上的onclick属性,改为页面加载完成后直接绑定点击事件,避免第一次点击仅做事件绑定。

2. 优化定时器调用

不需要在循环中重复调用setTimeout,只需要在所有动画层切换类之后调用一次即可,避免多次执行页面切换逻辑。

3. 减少重复DOM查询

提前获取需要操作的DOM元素,避免每次函数调用都重复查询。

修正后的完整代码

HTML

<button id="last">click</button>
<div id="main-cont">
  <h3>first page</h3>
</div>
<div id="overlay-cont">
  <div class="row">
    <div class="col-md-6 overlay-text" id="overlay-col">
      <h1>next page</h1>
    </div>
    <div class="col-md-6" id="overlay-col"></div>
  </div>
</div>
<div class="transition-cont">
  <div class="bottom-layer"></div>
  <div class="bottom-layer bottom-layer--2"></div>
  <div class="bottom-layer bottom-layer--3"></div>
</div>

JavaScript

document.addEventListener('DOMContentLoaded', function() {
  const button = document.querySelector("#last");
  const mainCont = document.getElementById("main-cont");
  const overlayCont = document.getElementById("overlay-cont");

  button.addEventListener("click", function() {
    const layers = document.querySelectorAll(".bottom-layer");
    layers.forEach(layer => layer.classList.toggle("active"));
    setTimeout(switchVisible, 900);
  });

  function switchVisible() {
    const isMainHidden = mainCont.style.display === "none";
    mainCont.style.display = isMainHidden ? "block" : "none";
    overlayCont.style.display = isMainHidden ? "none" : "block";
  }
});

CSS(保持原逻辑不变)

#overlay-cont {
  display: none;
  z-index: 1;
}

.bottom-layer {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 100%;
  left: 0;
  bottom: auto;
  right: auto;
  background: #48466d;
  transition: all 0.7s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.bottom-layer.active {
  top: -100%;
}

.bottom-layer--2 {
  background: #ecf3a3;
  transition-delay: 0.12s;
}

.bottom-layer--3 {
  background: #95a792;
  transition-delay: 0.4s;
}

额外说明

  • 原代码中循环调用setTimeout会导致switchVisible被执行三次,修正后只执行一次,避免不必要的DOM操作。
  • 使用DOMContentLoaded确保DOM元素加载完成后再绑定事件,避免出现找不到元素的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:45:33