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:
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>
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; }
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
swapIntervalto make the text swap faster or slower (e.g., 2000 for 2 seconds, 4000 for 4 seconds) - Add more phrases to the
textOptionsarray 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

