写一个方法判断页面滚动方向
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:
-
getScrollDirection()
Function (First Version):- Stores the previous vertical scroll position (
pageYOffset
) inpreviousScrollY
. - Attaches a
scroll
event listener to thewindow
. - Inside the listener:
- Gets the current scroll position (
currentScrollY
). - Compares
currentScrollY
withpreviousScrollY
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.
- Gets the current scroll position (
- Stores the previous vertical scroll position (
-
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.
- This version uses a closure to keep track of
-
Usage (Concise Version):
const isUp = getScrollDirectionConcise();
creates the closure and stores the returned function inisUp
.- Inside the
scroll
event listener, callingisUp()
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.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)