JS实现网页上下滑动
实现网页上下滑动的方法
监听滚动事件
通过监听窗口的scroll事件可以检测用户滚动行为。使用window.addEventListener绑定事件,通过window.scrollY获取垂直滚动位置。
window.addEventListener('scroll', function() {
console.log('当前滚动位置:', window.scrollY);
});
平滑滚动到指定位置
使用window.scrollTo()方法实现平滑滚动,通过behavior: 'smooth'启用动画效果。
function scrollToPosition(position) {
window.scrollTo({
top: position,
behavior: 'smooth'
});
}
滚动到页面顶部/底部
利用document.documentElement.scrollHeight获取页面总高度,实现滚动到底部功能。
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
function scrollToBottom() {
window.scrollTo({
top: document.documentElement.scrollHeight,
behavior: 'smooth'
});
}
元素滚动到视图中
使用Element.scrollIntoView()方法将特定DOM元素滚动到可视区域。
document.getElementById('target-element').scrollIntoView({
behavior: 'smooth'
});
自定义滚动动画
通过requestAnimationFrame实现自定义滚动动画,控制滚动速度和缓动效果。
function smoothScrollTo(targetPosition, duration = 1000) {
const startPosition = window.scrollY;
const distance = targetPosition - startPosition;
let startTime = null;
function animation(currentTime) {
if (!startTime) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const progress = Math.min(timeElapsed / duration, 1);
const ease = progress < 0.5
? 2 * progress * progress
: 1 - Math.pow(-2 * progress + 2, 2) / 2;
window.scrollTo(0, startPosition + distance * ease);
if (timeElapsed < duration) requestAnimationFrame(animation);
}
requestAnimationFrame(animation);
}
滚动节流优化
使用节流函数减少scroll事件触发频率,提升性能。
function throttle(func, limit = 100) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
window.addEventListener('scroll', throttle(function() {
console.log('节流后的滚动事件');
}));
滚动方向检测
通过比较当前和上次滚动位置判断滚动方向。
let lastScrollPosition = 0;
window.addEventListener('scroll', function() {
const currentScrollPosition = window.scrollY;
if (currentScrollPosition > lastScrollPosition) {
console.log('向下滚动');
} else {
console.log('向上滚动');
}
lastScrollPosition = currentScrollPosition;
});
滚动进度指示器
创建显示页面滚动进度的指示条。
const progressBar = document.createElement('div');
progressBar.style.position = 'fixed';
progressBar.style.top = '0';
progressBar.style.left = '0';
progressBar.style.height = '5px';
progressBar.style.backgroundColor = 'red';
progressBar.style.zIndex = '9999';
document.body.appendChild(progressBar);
window.addEventListener('scroll', function() {
const scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
const scrollProgress = (window.scrollY / scrollHeight) * 100;
progressBar.style.width = scrollProgress + '%';
});






