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

如何实现点击切换文本并添加淡入效果?

Add Fade-In Effect to Text Switching

Great question! Adding a smooth fade-in (and even a polished fade-out before switching) to your text changes is straightforward with CSS transitions paired with a small tweak to your JavaScript. Let’s break this down step by step:

Step 1: Add CSS for Fade Transitions

First, we’ll define transition styles so the browser knows to animate opacity changes. Drop this in your <head> section:

<style>
  .fade-text {
    /* Default state: fully visible */
    opacity: 1;
    /* Smooth transition for opacity adjustments */
    transition: opacity 0.5s ease;
  }

  .fade-text.fade-out {
    /* Faded-out state for the transition */
    opacity: 0;
  }
</style>

The 0.5s value controls how long the fade takes—tweak it to make the animation faster or slower as needed.

Step 2: Update Your HTML

Add the fade-text class to your text elements so the CSS applies to them:

<p id="demo" class="fade-text">text</p>
<p id="demo2" class="fade-text">text2</p>
<button onclick="changeText()">Change Texts</button>

Step 3: Modify the JavaScript Function

Instead of instantly swapping text, we’ll first fade out the elements, update the content once the fade-out finishes, then fade them back in. Here’s the updated function:

<script>
function changeText() {
  // Grab the target elements
  const demoEl = document.getElementById("demo");
  const demo2El = document.getElementById("demo2");

  // Trigger fade-out by adding the class
  demoEl.classList.add("fade-out");
  demo2El.classList.add("fade-out");

  // Wait for the fade-out to complete (matches the 0.5s transition time)
  setTimeout(() => {
    // Update the text content
    demoEl.innerHTML = "Newtext";
    demo2El.innerHTML = "Newtext2";

    // Trigger fade-in by removing the class
    demoEl.classList.remove("fade-out");
    demo2El.classList.remove("fade-out");
  }, 500);
}
</script>

How It Works

  1. When you click the button, we add the fade-out class to make the text transparent over 0.5 seconds.
  2. We wait 500ms (matching the transition duration) to let the fade-out finish before updating the text.
  3. Removing the fade-out class makes the new text fade back in smoothly.

If you only want a fade-in (no pre-switch fade-out), you could set initial opacity to 0, update the text, then toggle opacity to 1—but the fade-out + fade-in flow feels more polished for text switches!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:44:01