js实现滚屏
滚动到指定位置
使用 window.scrollTo() 方法实现精确滚动到页面某个坐标位置。该方法接受两个参数:X轴坐标和Y轴坐标。
window.scrollTo(0, 500); // 滚动到Y轴500像素处
添加平滑滚动效果可传入配置对象作为参数:
window.scrollTo({
top: 500,
left: 0,
behavior: 'smooth'
});
元素滚动到可视区域
通过 Element.scrollIntoView() 方法让特定元素滚动到浏览器可视区域。基本用法只需调用该方法:
document.getElementById('target').scrollIntoView();
添加平滑滚动参数:
document.getElementById('target').scrollIntoView({
behavior: 'smooth',
block: 'start' // 或 'center', 'end', 'nearest'
});
自定义滚动动画
使用 requestAnimationFrame 实现自定义滚动动画,提供更精细的控制:
function smoothScrollTo(targetY, duration = 1000) {
const startY = window.pageYOffset;
const distance = targetY - startY;
let startTime = null;
function animation(currentTime) {
if (!startTime) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const progress = Math.min(timeElapsed / duration, 1);
window.scrollTo(0, startY + distance * easeInOutQuad(progress));
if (timeElapsed < duration) requestAnimationFrame(animation);
}
function easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
}
requestAnimationFrame(animation);
}
滚动事件监听
监听滚动事件可实现滚动过程中的交互效果:
window.addEventListener('scroll', function() {
const scrollPosition = window.pageYOffset;
// 根据滚动位置执行操作
});
添加节流函数优化性能:
function throttle(fn, wait) {
let lastTime = 0;
return function() {
const now = Date.now();
if (now - lastTime >= wait) {
fn.apply(this, arguments);
lastTime = now;
}
};
}
window.addEventListener('scroll', throttle(function() {
console.log(window.pageYOffset);
}, 100));
滚动位置控制
获取当前滚动位置:
const scrollTop = window.pageYOffset
|| document.documentElement.scrollTop
|| document.body.scrollTop;
滚动到页面顶部:
window.scrollTo(0, 0);
// 或使用更简洁的写法
window.scrollTo({ top: 0, behavior: 'smooth' });
兼容性处理
针对旧版浏览器的polyfill方案:
// 平滑滚动polyfill
if (!('scrollBehavior' in document.documentElement.style)) {
require('smoothscroll-polyfill').polyfill();
}
滚动禁止与恢复
临时禁止页面滚动:
function disableScroll() {
document.body.style.overflow = 'hidden';
}
function enableScroll() {
document.body.style.overflow = '';
}
滚动条隐藏
隐藏滚动条但保持滚动功能:
::-webkit-scrollbar {
display: none;
}
无限滚动加载
实现滚动到底部自动加载内容:

window.addEventListener('scroll', function() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// 加载更多内容
}
});






