当前位置:首页 > JavaScript

js实现图片滚动效果

2026-01-13 14:42:14JavaScript

使用CSS动画实现图片滚动

通过CSS的@keyframesanimation属性实现无缝滚动效果。将图片容器设置为横向排列,通过动画平移位置。

<style>
  .scroll-container {
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
  }
  .scroll-content {
    display: inline-block;
    animation: scroll 20s linear infinite;
  }
  @keyframes scroll {
    0% { transform: translateX(0); }
    100% { transform: translateX(-50%); }
  }
</style>

<div class="scroll-container">
  <div class="scroll-content">
    <img src="image1.jpg" width="200">
    <img src="image2.jpg" width="200">
    <!-- 更多图片... -->
  </div>
  <div class="scroll-content" aria-hidden="true">
    <img src="image1.jpg" width="200">
    <img src="image2.jpg" width="200">
    <!-- 重复内容实现无缝滚动 -->
  </div>
</div>

使用JavaScript定时器实现

通过setInterval定期修改容器的scrollLeft属性实现平滑滚动。需计算内容宽度和滚动距离。

const container = document.querySelector('.scroll-container');
const content = document.querySelector('.scroll-content');
let scrollPos = 0;

function animate() {
  scrollPos += 1;
  if (scrollPos >= content.scrollWidth / 2) {
    scrollPos = 0;
  }
  container.scrollLeft = scrollPos;
  requestAnimationFrame(animate);
}

animate();

使用第三方库实现

Swiper.js等现成库提供丰富的滚动效果配置:

import Swiper from 'swiper';

new Swiper('.swiper-container', {
  loop: true,
  autoplay: {
    delay: 2500,
    disableOnInteraction: false,
  },
  slidesPerView: 'auto',
});

响应式处理注意事项

动态计算图片数量与容器宽度:

function initScroll() {
  const imgWidth = 200; // 单图宽度
  const visibleImgs = Math.ceil(container.offsetWidth / imgWidth);
  content.style.width = `${imgWidth * (images.length + visibleImgs)}px`;
}
window.addEventListener('resize', initScroll);

性能优化建议

使用will-change提升渲染性能:

.scroll-content {
  will-change: transform;
}

对于大量图片采用虚拟滚动技术,只渲染可视区域内的图片元素。滚动事件建议使用requestAnimationFrame而非直接setInterval

js实现图片滚动效果

标签: 效果图片
分享给朋友:

相关文章

vue实现图片查看

vue实现图片查看

Vue 实现图片查看功能 在 Vue 中实现图片查看功能,可以通过原生实现或使用第三方库。以下是几种常见的方法: 原生实现方式 使用 Vue 的指令和事件绑定实现基础的图片查看功能。 <…

vue实现图片循环

vue实现图片循环

实现图片循环的基本方法 在Vue中实现图片循环通常使用v-for指令结合数组数据。以下是基础实现方式: <template> <div> <img v-f…

vue实现预览效果

vue实现预览效果

Vue 实现预览效果的方法 使用 v-html 指令实现简单预览 在 Vue 中可以通过 v-html 指令直接将 HTML 字符串渲染到页面上,适用于简单的富文本预览场景。 <templat…

vue图片实现多选

vue图片实现多选

Vue图片多选实现方法 基础实现方案 使用v-model绑定数组配合input[type="checkbox"]实现多选功能。创建图片列表数据时,每个图片对象应包含唯一标识符: data() {…

网页制作css图片切换

网页制作css图片切换

CSS图片切换的实现方法 使用CSS实现图片切换可以通过多种方式完成,以下是几种常见的方法: 纯CSS轮播图 通过CSS动画和关键帧实现自动轮播效果。定义一个容器,内部放置多个图片,利用anima…

网页设计制作css图片

网页设计制作css图片

CSS图片处理基础方法 在网页设计中,CSS可以控制图片的尺寸、位置、边框等样式属性。通过<img>标签或背景图方式引入图片后,使用CSS属性进行调整。 img { width:…