如何为多个元素设置Waypoints?滚动触发动画实现咨询
Awesome question—scaling your scroll-triggered animations to multiple elements is totally doable with a few small tweaks to your existing setup. Let's break it down step by step:
First, give all elements that need scroll animations a shared base class (like animate-on-scroll) alongside their unique classes. This lets you target them all at once while keeping individual styling flexibility:
<div class="dipper animate-on-scroll"> <p>Peekaboo</p> </div> <div class="fox animate-on-scroll"> <p>Hi there!</p> </div> <div class="bear animate-on-scroll"> <p>Grrr!</p> </div>
Instead of targeting a single element, we'll loop through all elements with our shared class and attach Waypoints to each one individually. Here are two versions depending on whether you prefer vanilla JS or jQuery:
Vanilla JS Version (Lightweight, No jQuery Dependency)
// Wait for the DOM to fully load before initializing document.addEventListener('DOMContentLoaded', function() { // Grab all elements that need scroll animations const animatedElements = document.querySelectorAll('.animate-on-scroll'); // Attach Waypoints to each element animatedElements.forEach(element => { new Waypoint({ element: element, handler: function(direction) { if (direction === 'down') { this.element.classList.add('js-animate'); } else { this.element.classList.remove('js-animate'); } }, offset: '75%' // Keep your existing trigger point, adjust as needed }); }); });
jQuery Version (If You're Sticking With jQuery)
$(document).ready(function() { // Loop through each animated element $('.animate-on-scroll').each(function() { const $element = $(this); $element.waypoint(function(direction) { if (direction === 'down') { $element.addClass('js-animate'); } else { $element.removeClass('js-animate'); } }, { offset: '75%' }); }); });
You can now create a base animation style for all elements, plus unique tweaks for individual classes:
/* Base style: hidden until triggered */ .animate-on-scroll { opacity: 0; transition: all 0.6s ease-out; } /* Triggered state: show the element */ .animate-on-scroll.js-animate { opacity: 1; } /* Unique animation for .dipper */ .dipper { transform: translateY(20px); } .dipper.js-animate { transform: translateY(0); } /* Unique animation for .fox */ .fox { transform: translateX(-20px); } .fox.js-animate { transform: translateX(0); }
- Custom Offsets Per Element: Add a
data-offsetattribute to elements that need a different trigger point, then read it in your script:<div class="owl animate-on-scroll" data-offset="50%">...</div>// In the Waypoint config: offset: element.dataset.offset || '75%' - One-Time Animations: If you don't want animations to reverse when scrolling up, just remove the
elseblock that removes thejs-animateclass. - Performance: For large numbers of elements, consider using the native
IntersectionObserverAPI instead of Waypoints—it's more performant, but Waypoints is still great for simpler use cases.
内容的提问来源于stack exchange,提问作者Devon Stuper

