如何在经过#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#boxcontainer.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,#boxhasn'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 the100to make the fade faster or slower). - Binding to both
loadandscrollensures the opacity is set correctly when the page first loads (even if#boxis 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
相关产品推荐
相关产品推荐

