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

H1标签内文本实时切换替换功能实现咨询

Hey there! Let's walk through how to create that dynamic text swap effect in your H1 tag—this is a great way to add some flair to your hero section, just like the example you referenced. I'll show you a vanilla JavaScript approach (no frameworks needed) that's clean and easy to tweak:

Step 1: Set Up Your HTML Structure

First, wrap the part of the text you want to swap in a <span> with a class so we can target it easily:

<h1>Hi, I am Udim Manny, <span class="dynamic-text">' I design landing pages'</span></h1>
Step 2: Add Smooth Transitions with CSS

To make the text swap feel natural (not just a jarring jump), add a fade-in/fade-out transition. This will soften the switch between phrases:

/* Base styles for the dynamic text */
.dynamic-text {
  transition: opacity 0.3s ease-in-out;
}

/* Class to trigger fade-out */
.fade-out {
  opacity: 0;
}
Step 3: Implement the Text Swap Logic with JavaScript

Now we'll write a simple script to cycle through your text options, using the CSS transition to make the swap smooth:

// Grab the span we want to update
const dynamicTextElement = document.querySelector('.dynamic-text');
// List of phrases to cycle through
const textOptions = ["' I design landing pages'", "' I build websites'"];
// Track which phrase we're currently showing
let currentPhraseIndex = 0;
// How long to wait between swaps (in milliseconds—3000 = 3 seconds)
const swapInterval = 3000;

function swapDynamicText() {
  // Trigger the fade-out effect
  dynamicTextElement.classList.add('fade-out');

  // Wait for the fade-out transition to finish, then update the text and fade back in
  setTimeout(() => {
    // Move to the next phrase (loop back to the start when we reach the end)
    currentPhraseIndex = (currentPhraseIndex + 1) % textOptions.length;
    // Update the text content
    dynamicTextElement.textContent = textOptions[currentPhraseIndex];
    // Remove the fade-out class to trigger fade-in
    dynamicTextElement.classList.remove('fade-out');
  }, 300); // Match this to your CSS transition duration (0.3s = 300ms)
}

// Start the cycle—run the swap function initially, then repeat every swapInterval
setInterval(swapDynamicText, swapInterval);

Quick Notes to Customize:

  • Adjust swapInterval to make the text swap faster or slower (e.g., 2000 for 2 seconds, 4000 for 4 seconds)
  • Add more phrases to the textOptions array if you want to cycle through more than two
  • Tweak the CSS transition duration (0.3s) to make the fade effect quicker or slower

This approach is lightweight, works across all modern browsers, and is easy to modify if you want to add extra touches like typing effects later.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:32:19