jquery滚动
jQuery 滚动事件监听
使用 jQuery 监听滚动事件可以通过 scroll() 方法实现。以下是一个基本示例,当用户滚动页面时触发回调函数:
$(window).scroll(function() {
console.log('页面正在滚动');
});
获取滚动位置
通过 scrollTop() 方法可以获取当前垂直滚动条的位置。结合 scroll() 事件,可以实时监测滚动位置:
$(window).scroll(function() {
var scrollPosition = $(window).scrollTop();
console.log('当前滚动位置: ' + scrollPosition + 'px');
});
平滑滚动到指定位置
使用 animate() 方法可以实现平滑滚动到页面的某个位置。以下代码演示如何滚动到距离顶部 500px 的位置:
$('html, body').animate({
scrollTop: 500
}, 800); // 800 毫秒内完成动画
滚动到页面顶部或底部
滚动到页面顶部可以通过设置 scrollTop 为 0 实现:
$('html, body').animate({
scrollTop: 0
}, 800);
滚动到页面底部可以通过获取文档高度实现:

$('html, body').animate({
scrollTop: $(document).height()
}, 800);
滚动到特定元素位置
通过获取目标元素的偏移位置,可以实现滚动到该元素的功能:
$('button').click(function() {
$('html, body').animate({
scrollTop: $('#target-element').offset().top
}, 800);
});
滚动事件优化
频繁触发滚动事件可能影响性能,可以通过节流(throttling)优化:
var timer;
$(window).scroll(function() {
clearTimeout(timer);
timer = setTimeout(function() {
console.log('滚动结束');
}, 200);
});
检测滚动方向
通过比较当前和上一次的滚动位置,可以判断滚动方向:

var lastScrollTop = 0;
$(window).scroll(function() {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
console.log('向下滚动');
} else {
console.log('向上滚动');
}
lastScrollTop = st;
});
固定导航栏效果
结合滚动事件和 CSS,可以实现滚动时固定导航栏的效果:
$(window).scroll(function() {
if ($(window).scrollTop() > 100) {
$('nav').addClass('fixed');
} else {
$('nav').removeClass('fixed');
}
});
CSS 部分:
.fixed {
position: fixed;
top: 0;
width: 100%;
z-index: 1000;
}
懒加载图片
滚动事件可以用于实现图片懒加载,当图片进入可视区域时加载:
$(window).scroll(function() {
$('img.lazy').each(function() {
if (isElementInViewport(this)) {
$(this).attr('src', $(this).data('src'));
$(this).removeClass('lazy');
}
});
});
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}





