怎样用JS实现横向或纵向的无缝滚动效果?

8 min read

好的,可以使用以下代码实现:

HTML:

<div class="scroll-container">
  <div class="scroll-content">
    <img src="image1.jpg" alt="">
    <img src="image2.jpg" alt="">
    <img src="image3.jpg" alt="">
  </div>
</div>

CSS:

.scroll-container {
  width: 100%;
  height: 200px;
  overflow: hidden;
  position: relative;
}
.scroll-content {
  position: absolute;
  white-space: nowrap; /* 防止图片换行 */
  animation: scroll 30s linear infinite; /* 控制速度和循环 */
}
.scroll-content img {
  display: inline-block;
  height: 100%;
  margin-right: 20px;
}

JavaScript:

const scrollContent = document.querySelector('.scroll-content');

// 动态计算 scrollContent 的宽度
let imgWidth = 200; // 假设图片宽度为 200px
let numImgs = scrollContent.childElementCount;
scrollContent.style.width = `${imgWidth * numImgs}px`;

// 创建 Animation Keyframe,控制无限滚动
let keyFrame = '';

for (let i = 0; i < numImgs; i++) {
  keyFrame += `${100 / numImgs * i}% { transform: translateX(-${imgWidth * i}px); }`;
}

keyFrame += `100% { transform: translateX(${imgWidth}px); }`;

// 将 keyFrame 加入 style 标签中
const style = document.createElement('style');
style.innerHTML = `
  @keyframes scroll {
    ${keyFrame}
  }
`;
document.head.appendChild(style);

以上代码实现了横向无缝滚动效果,如果需要纵向滚动,只需要将 CSS 中的 white-space: nowrap; 换成 display: flex; flex-direction: column; 即可。