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

如何在经过#box容器而非页面顶部时触发jQuery透明度计数?

Solution to Trigger Opacity Change Only When Scrolling to #box

The issue with your current code is that it uses the page's total scroll distance right from the top. To fix this, we need to calculate the scroll position relative to your #box container—so we only start adjusting the opacity once the user has scrolled to the top of #box.

Here's the modified script that does exactly that:

function parallaxFade() {
  const scrollPos = $(window).scrollTop();
  const boxTop = $('#box').offset().top;
  const relativeScroll = scrollPos - boxTop;
  
  // Calculate opacity based on how far we've scrolled past #box
  let opacity = 1;
  if (relativeScroll > 0) {
    // Fade out gradually as we scroll (adjust 100 to control fade speed)
    opacity = Math.max(0, 1 - (relativeScroll / 100));
  }
  
  $('#boxtext').css({ 'opacity': opacity });
}

// Run the function on page load and every time the user scrolls
$(window).on('load scroll', parallaxFade);

How this works:

  • scrollPos: Tracks how far the user has scrolled from the top of the entire page.
  • boxTop: Gets the distance from the top of the document to the top of your #box container.
  • relativeScroll: This is the key value—it tells us how far the user has scrolled past the top of #box. If this number is negative, #box hasn't reached the viewport yet.
  • We keep the opacity at 1 until the user scrolls past #box. Once they do, we decrease the opacity linearly until it hits 0 after scrolling 100px beyond #box's top (you can change the 100 to make the fade faster or slower).
  • Binding to both load and scroll ensures the opacity is set correctly when the page first loads (even if #box is already visible) and updates as the user scrolls.

Your HTML can stay exactly as it is:

<div class="box" id="box"> <h3 class="boxtext" id="boxtext">Heading</h3> </div>

内容的提问来源于stack exchange,提问作者Edvin Uddfalk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:37:29