Fullpage.js切换章节时触发自定义CSS遮罩动画需求
Got it, let's work through this together. You want that white mask animation to fire exactly once every time Fullpage.js switches sections—here's a straightforward, reliable way to make that happen:
1. HTML Structure
First, add the mask element to your page (stick it at the end of your <body> since it's absolutely positioned):
<div class="mask-white"></div>
2. CSS Adjustments
We'll split the base mask styles from the animation class so we can toggle the animation on demand (this prevents it from running on page load):
/* Base mask styles (always active) */ .mask-white { width: 100vw; background-color: white; position: absolute; top: 0; left: 0; z-index: 22222; height: 0vh; /* Start hidden */ bottom: 0; /* Match animation's starting state */ } /* Animation class to trigger the effect */ .mask-animate { animation: height-white 1s forwards; } @keyframes height-white { 0% { height: 0vh; bottom: 0; top: auto; /* Override base top property here */ } 50% { height: 100vh; } 100% { height: 0vh; top: auto; bottom: 0; } }
The forwards keyword ensures the mask stays in its final state (height: 0) after the animation finishes.
3. JavaScript Implementation
We'll use Fullpage.js's onLeave callback (triggers when you start switching sections) to kick off the animation, and reset the mask properly so it can run again on the next transition:
// Initialize Fullpage.js with your custom options new fullpage('#fullpage', { // Add your existing Fullpage settings here (e.g., section colors, navigation) sectionsColor: ['#f2f2f2', '#4BBFC3', '#7BAABE'], onLeave: function(origin, destination, direction) { const mask = document.querySelector('.mask-white'); // Reset the animation state first (critical for re-triggering) mask.classList.remove('mask-animate'); // Force a browser reflow to reset the animation timeline void mask.offsetWidth; // Add the animation class to start the effect mask.classList.add('mask-animate'); // Clean up: Remove the animation class once it finishes mask.addEventListener('animationend', () => { mask.classList.remove('mask-animate'); }, { once: true }); // Ensures we don't pile up event listeners } });
Quick Breakdown of Key Bits:
onLeaveCallback: This fires every time you initiate a section switch—perfect for triggering a transition animation.- Animation Reset: Removing the class and forcing a reflow (
void mask.offsetWidth) tricks the browser into treating the animation as a new instance, so it runs from the start every time. animationendListener: Cleans up the animation class after it finishes, keeping the DOM tidy and ready for the next trigger.
内容的提问来源于stack exchange,提问作者user8690699

