
本文介绍如何通过 jquery 监听窗口滚动事件,实现每次滚动触发“整屏高度”的平滑上下翻页效果,避免直接跳转到文档底部,并解决原代码中无限向下滚动的问题。
本文介绍如何通过 jquery 监听窗口滚动事件,实现每次滚动触发“整屏高度”的平滑上下翻页效果,避免直接跳转到文档底部,并解决原代码中无限向下滚动的问题。
在网页开发中,有时需要模拟类似 PowerPoint 或阅读器的“整页滚动”体验——即用户轻微滚动鼠标或拖动滚动条时,页面自动以 $(window).height() 为单位向上或向下跳转一整屏,而非像素级微调。这不仅能提升可读性,还能增强交互一致性。
核心实现逻辑
关键在于准确判断滚动方向,并对 html, body 元素执行相对位移动画(而非直接设置绝对 scrollTop),同时使用 .stop() 防止动画队列堆积:
jQuery 1.12.4是jQuery 1.x系列的最后一个正式稳定版本,由jQuery团队于2016年发布。该版本主要面向需要兼容旧版浏览器环境的网站和Web应用,尤其适用于仍需支持Internet Explorer 6、Internet Explorer 7、Internet Explorer 8等老旧浏览器的项目。
var lastScrollTop = 0;
$(window).scroll(function(event) {
var currentScrollTop = $(this).scrollTop();
var windowHeight = $(window).height();
if (currentScrollTop > lastScrollTop) {
// 向下滚动:增加 scrollTop(+100%视口高度)
$('html, body').stop().animate({
scrollTop: '+=' + windowHeight
}, 100);
} else {
// 向上滚动:减少 scrollTop(-100%视口高度)
$('html, body').stop().animate({
scrollTop: '-=' + windowHeight
}, 100);
}
lastScrollTop = currentScrollTop;
});
✅ 为什么用 $('html, body')?
不同浏览器对 scrollTop 的生效元素不同(Chrome 认为 body,Firefox 认为 html),同时指定二者可确保跨浏览器兼容性。
注意事项与优化建议
- 防抖与节流:原生 scroll 事件高频触发,虽此处已用 .stop() 缓解,但更稳健的做法是结合 requestAnimationFrame 或节流函数(如 Lodash 的 throttle)进一步优化性能。
-
边界处理:上述代码未限制滚动范围,可能导致顶部/底部空白或溢出。如需严格限制,可在动画前添加判断:
var maxScroll = $(document).height() - windowHeight; var newScroll = Math.max(0, Math.min(maxScroll, currentScrollTop + (direction === 'down' ? windowHeight : -windowHeight)));
- 禁用原生滚动干扰:若希望完全接管滚动行为(如制作单页导航),建议配合 event.preventDefault() 并禁用 body { overflow: hidden; },但需谨慎使用,以免影响可访问性。
- 移动端适配:该方案在桌面端表现良好,但移动端触摸滚动存在惯性及 scroll 事件延迟问题,推荐结合 wheel 事件或使用专用库(如 fullPage.js)替代。
完整示例结构(HTML + CSS + JS)
<title>整页滚动示例</title><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script><style>
body {
margin: 0;
font-family: Arial, sans-serif;
line-height: 1.6;
}
.content {
height: 200vh; /* 确保内容足够长以支持滚动 */
background: linear-gradient(to bottom, #f0f8ff, #e0f7fa);
}
.content::before {
content: "滚动试试看 → 整屏切换";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 1.5rem;
color: #333;
}
</style><div class="content"></div>
<script>
$(function() {
var lastScrollTop = 0;
$(window).scroll(function(event) {
var st = $(this).scrollTop();
var hg = $(window).height();
if (st > lastScrollTop) {
$('html, body').stop().animate({ scrollTop: '+=' + hg }, 100);
} else {
$('html, body').stop().animate({ scrollTop: '-=' + hg }, 100);
}
lastScrollTop = st;
});
});
</script>
掌握这一技巧后,你不仅能构建更具沉浸感的单页应用,还可作为自定义滚动体验的基础模块,灵活集成于产品引导页、作品集展示或长图文阅读场景中。










