怎么用js实现滚动播放
使用原生JavaScript实现滚动播放
监听滚动事件
通过window.addEventListener监听scroll事件,获取当前滚动位置window.scrollY或window.pageYOffset。结合requestAnimationFrame优化性能,避免滚动卡顿。
let lastScrollPosition = 0;
function handleScroll() {
const currentScroll = window.pageYOffset;
// 滚动方向判断
const direction = currentScroll > lastScrollPosition ? 'down' : 'up';
lastScrollPosition = currentScroll;
requestAnimationFrame(handleScroll);
}
window.addEventListener('scroll', handleScroll);
自动滚动动画
使用window.scrollTo方法配合缓动函数实现平滑滚动。通过递归调用实现连续滚动效果。
function autoScroll(targetY, duration = 1000) {
const startY = window.pageYOffset;
const distance = targetY - startY;
let startTime = null;
function animation(currentTime) {
if (!startTime) startTime = currentTime;
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const ease = progress < 0.5
? 2 * progress * progress
: 1 - Math.pow(-2 * progress + 2, 2) / 2;
window.scrollTo(0, startY + distance * ease);
if (elapsed < duration) requestAnimationFrame(animation);
}
requestAnimationFrame(animation);
}
使用CSS动画实现滚动
关键帧动画定义
通过CSS的@keyframes定义滚动动画,结合transform属性实现性能优化的硬件加速动画。

@keyframes scrollAnimation {
0% { transform: translateY(0); }
100% { transform: translateY(-100%); }
}
.scroll-container {
animation: scrollAnimation 10s linear infinite;
overflow: hidden;
}
动态内容更新 使用JavaScript动态更新内容容器的高度,确保无缝循环滚动。
const container = document.querySelector('.scroll-container');
function updateContent() {
const firstChild = container.children[0];
container.appendChild(firstChild.cloneNode(true));
container.removeChild(firstChild);
}
setInterval(updateContent, 5000);
实现无限循环滚动
DOM节点复用技术 当元素滚动出可视区域时,将其移动到列表末尾,保持DOM节点数量恒定,提高性能。

const list = document.getElementById('infinite-list');
function scrollHandler() {
const firstItem = list.firstElementChild;
if (firstItem.getBoundingClientRect().bottom < 0) {
list.appendChild(firstItem);
}
}
list.addEventListener('scroll', scrollHandler);
滚动位置重置 当滚动接近底部时,瞬间重置滚动位置到顶部,制造无限循环的假象。
const wrapper = document.querySelector('.infinite-wrapper');
wrapper.addEventListener('scroll', () => {
if (wrapper.scrollTop >= wrapper.scrollHeight - wrapper.clientHeight) {
wrapper.scrollTop = 1;
} else if (wrapper.scrollTop <= 0) {
wrapper.scrollTop = wrapper.scrollHeight - wrapper.clientHeight - 1;
}
});
响应式滚动控制
触摸事件处理
添加touchstart和touchmove事件监听器,确保在移动设备上也能正常控制滚动。
let touchStartY = 0;
document.addEventListener('touchstart', (e) => {
touchStartY = e.touches[0].clientY;
}, { passive: true });
document.addEventListener('touchmove', (e) => {
const touchY = e.touches[0].clientY;
const diff = touchStartY - touchY;
window.scrollBy(0, diff);
touchStartY = touchY;
}, { passive: false });
滚动节流优化
使用setTimeout或requestAnimationFrame实现滚动事件节流,防止性能问题。
let isScrolling = false;
window.addEventListener('scroll', () => {
if (!isScrolling) {
isScrolling = true;
setTimeout(() => {
// 执行滚动相关操作
isScrolling = false;
}, 100);
}
});






