js实现图片滚动
实现图片滚动的JavaScript方法
使用CSS动画结合JavaScript控制
通过CSS定义动画效果,JavaScript控制动画的启停或方向。CSS的@keyframes和animation属性可实现平滑滚动。
.scroll-container {
width: 100%;
overflow: hidden;
white-space: nowrap;
}
.scroll-content {
display: inline-block;
animation: scroll 10s linear infinite;
}
@keyframes scroll {
0% { transform: translateX(0); }
100% { transform: translateX(-50%); }
}
const container = document.querySelector('.scroll-container');
container.addEventListener('mouseenter', () => {
container.querySelector('.scroll-content').style.animationPlayState = 'paused';
});
container.addEventListener('mouseleave', () => {
container.querySelector('.scroll-content').style.animationPlayState = 'running';
});
使用JavaScript定时器实现滚动
通过setInterval动态修改元素的transform或margin属性,实现逐帧滚动效果。

const content = document.querySelector('.scroll-content');
let position = 0;
const speed = 1;
function scrollImages() {
position -= speed;
if (position <= -content.scrollWidth / 2) {
position = 0;
}
content.style.transform = `translateX(${position}px)`;
}
const interval = setInterval(scrollImages, 16);
document.querySelector('.scroll-container').addEventListener('mouseenter', () => {
clearInterval(interval);
});
使用requestAnimationFrame优化性能
相比setInterval,requestAnimationFrame能更好地与浏览器刷新率同步,避免卡顿。
let animationId;
let position = 0;
const content = document.querySelector('.scroll-content');
function animate() {
position -= 1;
if (position <= -content.scrollWidth / 2) {
position = 0;
}
content.style.transform = `translateX(${position}px)`;
animationId = requestAnimationFrame(animate);
}
animationId = requestAnimationFrame(animate);
document.querySelector('.scroll-container').addEventListener('mouseenter', () => {
cancelAnimationFrame(animationId);
});
无缝循环滚动的实现技巧
克隆滚动内容并拼接,当滚动到克隆部分时重置位置,实现视觉上的无缝衔接。

const container = document.querySelector('.scroll-container');
const content = document.querySelector('.scroll-content');
content.innerHTML += content.innerHTML; // 克隆内容
function scroll() {
container.scrollLeft += 1;
if (container.scrollLeft >= content.scrollWidth / 2) {
container.scrollLeft = 0;
}
}
const interval = setInterval(scroll, 16);
响应式设计的注意事项
通过监听窗口大小变化,动态调整滚动速度或容器尺寸。
window.addEventListener('resize', () => {
const containerWidth = document.querySelector('.scroll-container').offsetWidth;
// 根据容器宽度调整滚动参数
});
触摸设备支持
添加touchstart和touchend事件处理,确保在移动设备上也能正常交互。
const container = document.querySelector('.scroll-container');
container.addEventListener('touchstart', () => {
// 暂停滚动
});
container.addEventListener('touchend', () => {
// 恢复滚动
});






