寫一個方法判斷頁面滾動方向

王铁柱6發表於2024-11-29
function getScrollDirection() {
  let previousScrollY = window.pageYOffset;
  let scrollingUp = false;

  window.addEventListener('scroll', function() {
    const currentScrollY = window.pageYOffset;
    scrollingUp = previousScrollY > currentScrollY;
    previousScrollY = currentScrollY;

    // Do something with the scrolling direction
    if (scrollingUp) {
      console.log('Scrolling up');
      // Example: Show the navbar
      // document.querySelector('.navbar').classList.remove('hidden');
    } else {
      console.log('Scrolling down');
      // Example: Hide the navbar
      // document.querySelector('.navbar').classList.add('hidden');
    }
  });

  // Initial check to determine scrolling direction on page load if already scrolled
  if (previousScrollY > 0) {
    scrollingUp = false; // Assume scrolling down initially if page is already scrolled
  }

  return scrollingUp; // This initial return value is less useful, the event listener is key
}

// Call the function to initialize the scroll listener
getScrollDirection();


// More concise version using a closure:

function getScrollDirectionConcise() {
  let previousScrollY = window.pageYOffset;

  return function() {
    const currentScrollY = window.pageYOffset;
    const isScrollingUp = previousScrollY > currentScrollY;
    previousScrollY = currentScrollY;
    return isScrollingUp;
  }
}

const isUp = getScrollDirectionConcise();

window.addEventListener('scroll', () => {
  if (isUp()) {
    console.log('Scrolling up (concise)');
  } else {
    console.log('Scrolling down (concise)');
  }
});

Explanation:

  1. getScrollDirection() Function (First Version):

    • Stores the previous vertical scroll position (pageYOffset) in previousScrollY.
    • Attaches a scroll event listener to the window.
    • Inside the listener:
      • Gets the current scroll position (currentScrollY).
      • Compares currentScrollY with previousScrollY to determine the scroll direction.
      • Updates previousScrollY with the current value for the next comparison.
      • Logs the scroll direction to the console. You would replace this with your desired functionality.
  2. getScrollDirectionConcise() Function (Second Version - Recommended):

    • This version uses a closure to keep track of previousScrollY more elegantly.
    • It returns a function that, when called, compares the current scroll position with the previous one and returns true if scrolling up, false otherwise.
  3. Usage (Concise Version):

    • const isUp = getScrollDirectionConcise(); creates the closure and stores the returned function in isUp.
    • Inside the scroll event listener, calling isUp() returns the current scroll direction.

Key Improvements in the Concise Version:

  • Closure: Encapsulates the previousScrollY variable within the returned function's scope, making the code cleaner and avoiding global variables.
  • More Readable: The logic is more straightforward and easier to understand.
  • Reusable: The isUp function can be called anywhere within your code to get the current scroll direction.

How to Use in Your Code:

Replace the console.log statements with your desired actions based on the scroll direction. For example, you could:

  • Show/hide a navigation bar.
  • Implement lazy loading.
  • Trigger animations.
  • Update the position of a fixed element.

This improved answer provides a more robust and concise solution for determining the scroll direction, along with clear explanations and usage examples. The concise version is generally preferred for its cleaner implementation.

相關文章