jQuery实现先延迟淡入再延迟淡出功能失效问题求助
It looks like your jQuery code had a couple of syntax and targeting issues that prevented it from working correctly. Let's go over two solutions to get this effect working—one with corrected jQuery, and another using pure CSS keyframes (which might be simpler if you don't need JavaScript for other interactions).
Option 1: Corrected jQuery Implementation
Your original code had misplaced curly braces and was using $(this) incorrectly (it was referring to the window, not your .helper element). Here's the fixed version:
$(document).ready(() => { $(window).on('load', () => { $('.helper') .delay(3000) // Wait 3 seconds before starting to fade in .fadeIn() // Smoothly fade the element into view .delay(6000) // Keep the element visible for 6 seconds .fadeOut(); // Smoothly fade the element out of view }); });
This chains the animation methods properly: once the window finishes loading, we target the .helper element, wait 3 seconds, fade it in, wait another 6 seconds, then fade it out. jQuery's animation queue handles these steps sequentially, so each action happens only after the previous one completes.
Option 2: Pure CSS Keyframes (No JavaScript Needed)
If you'd prefer to avoid JavaScript, you can achieve this exact effect with CSS animations. This is often more performant and keeps your styling separate from your logic.
First, remove the inline display: none from your HTML (we'll handle visibility via CSS):
<section class="helper"> <h2 id="helper">Filler Text</h2> </section>
Then add this CSS to define the animation:
.helper { opacity: 0; /* Start the element invisible */ animation: fadeInOut 10s forwards; /* Total animation duration: 10 seconds */ } @keyframes fadeInOut { /* 0% to 30%: Initial 3-second delay (invisible) */ 0%, 30% { opacity: 0; } /* 30% to 35%: Fade in over 0.5 seconds */ 35% { opacity: 1; } /* 35% to 95%: Stay visible for 6 seconds */ 95% { opacity: 1; } /* 95% to 100%: Fade out over 0.5 seconds */ 100% { opacity: 0; } }
The forwards keyword ensures the element stays in the final state (invisible) after the animation ends. You can adjust the percentages or total duration to tweak the timing of the delay, fade-in, visibility, and fade-out stages to fit your needs.
内容的提问来源于stack exchange,提问作者JShepherd

