jQuery实现滚动时为parallax区块动态增删link类问题求助
Fix for Parallax Scroll Class Toggle Issue
Hey there, let's break down why your code is throwing that error and fix it to work with all your .parallax blocks:
What's Wrong with the Original Code?
You've got two key issues here:
- Only targeting the first
.parallaxelement:$('.parallax').attr('id')grabs the ID of just the first matching element, so all other blocks are completely ignored. - Broken selector syntax: When you do
$('#parallax'+target), iftargetisparallax-1, you end up with a selector like#parallaxparallax-1—which doesn't match any of your actual elements (your IDs areparallax-1,parallax-2, etc.). That's why$divreturnsundefined, causing theoffset().toperror.
Corrected Code
Here's the fixed version that works reliably for all your .parallax blocks:
const $window = $(window); const $parallaxBlocks = $('.parallax'); // Function to check scroll position and update classes function updateParallaxClasses() { const scrollTop = $window.scrollTop(); // Loop through each parallax block individually $parallaxBlocks.each(function() { const $block = $(this); const blockTop = $block.offset().top; // Toggle the 'link' class based on scroll position if (scrollTop >= blockTop) { $block.addClass('link'); } else { $block.removeClass('link'); } }); } // Attach the function to load, resize, and scroll events $window.on('load resize scroll', updateParallaxClasses); // Run once on initial load to set the correct state immediately updateParallaxClasses();
Key Improvements Explained
- Iterate over all blocks: Using
.each()ensures every.parallaxelement is checked and updated, not just the first one. - Direct block reference: Instead of messing with ID strings, we use
$(this)inside the loop to target the current block—no more broken selector mistakes. - Efficient DOM queries: Storing
$parallaxBlocksin a variable avoids re-querying the DOM every time the event fires, which boosts performance. - Initial state setup: Calling
updateParallaxClasses()on load ensures the correct class is applied right away, not just after the first scroll action.
内容的提问来源于stack exchange,提问作者Mathieu Préaud
相关产品推荐
相关产品推荐

