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

扩展滚动淡入淡出代码:实现上下滚动全场景元素淡入淡出效果

Got it, let's get this sorted so your elements fade in and out properly no matter which way you scroll! Your original code only handles one direction of scroll and one type of visibility change, so we'll expand it to cover every scenario: elements fade in when entering the viewport (from top or bottom) and fade out when exiting (to top or bottom).

Full-Scroll Direction Fade In/Out for Elements

We'll use CSS transitions for smooth animations and JavaScript to track element visibility relative to the viewport on every scroll event.

Step 1: Base CSS (Transitions & Initial State)

First, set up a hidden default state and smooth transitions for opacity (plus optional transform for extra movement):

.fade-element {
  opacity: 0;
  transform: translateY(20px);
  /* Smooth transition for both opacity and position */
  transition: opacity 0.6s ease-in-out, transform 0.6s ease-in-out;
}

.fade-element.visible {
  opacity: 1;
  transform: translateY(0);
}

Step 2: JavaScript Logic (Full Visibility Detection)

This script will check each element's position on scroll, resize, and initial load to handle all visibility scenarios:

const fadeElements = document.querySelectorAll('.fade-element');

function checkElementVisibility() {
  fadeElements.forEach(element => {
    const rect = element.getBoundingClientRect();
    const viewportHeight = window.innerHeight;

    // Check if any part of the element is inside the viewport
    const isPartiallyVisibleFromTop = rect.top < viewportHeight && rect.top > 0;
    const isPartiallyVisibleFromBottom = rect.bottom > 0 && rect.bottom < viewportHeight;
    const isFullyVisible = rect.top >= 0 && rect.bottom <= viewportHeight;

    // Combine all visibility checks
    const isInViewport = isPartiallyVisibleFromTop || isPartiallyVisibleFromBottom || isFullyVisible;

    // Toggle visibility class based on viewport status
    if (isInViewport) {
      element.classList.add('visible');
    } else {
      element.classList.remove('visible');
    }
  });
}

// Run on initial page load to show elements already in view
window.addEventListener('load', checkElementVisibility);
// Run on every scroll event
window.addEventListener('scroll', checkElementVisibility);
// Run on viewport resize (e.g., mobile rotation)
window.addEventListener('resize', checkElementVisibility);

Step 3: HTML Example

Add the fade-element class to any element you want to animate:

<div class="content">
  <div class="fade-element">Element 1: Fades in when entering (top/bottom), fades out when exiting</div>
  <div class="fade-element">Element 2: Works seamlessly on up/down scroll</div>
  <!-- Spacer to test full scroll behavior -->
  <div style="height: 150vh;"></div>
  <div class="fade-element">Element 3: Fades in when scrolling up to it, fades out when scrolling past</div>
</div>

Key Improvements Over Your Original Code

  • Full direction support: Handles both upward and downward scrolling without bias
  • Exit detection: Triggers fade-out when elements leave the viewport from either top or bottom
  • Initial load check: Ensures elements already visible on page load aren't stuck hidden
  • Resize support: Updates visibility if the viewport size changes

Optional: Fine-Tune Visibility Threshold

If you want elements to start fading in only when a portion of them is visible (e.g., 20% of the element), adjust the visibility logic:

// Example: Start fade-in when 20% of the element is in view
const visibilityThreshold = 0.2;
const elementHeight = rect.height;
// Calculate how many pixels of the element are visible
const visiblePixels = Math.max(0, Math.min(viewportHeight, rect.bottom) - Math.max(0, rect.top));
const visibilityRatio = visiblePixels / elementHeight;

const isInViewport = visibilityRatio >= visibilityThreshold;

内容的提问来源于stack exchange,提问作者Mr.Rlover

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:53:12