You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 .parallax element: $('.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), if target is parallax-1, you end up with a selector like #parallaxparallax-1—which doesn't match any of your actual elements (your IDs are parallax-1, parallax-2, etc.). That's why $div returns undefined, causing the offset().top error.

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 .parallax element 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 $parallaxBlocks in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:22:09