当前位置:首页 > 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提升渲染性能:

js实现图片滚动效果

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

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

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

相关文章

react如何引用图片

react如何引用图片

在React中引用图片的方法 使用import直接引入图片 在React组件中,可以通过import语句将图片作为模块引入。这种方式适合在组件内部使用图片,Webpack会处理图片的路径和打包。 i…

js图片轮播的实现

js图片轮播的实现

基础图片轮播实现 使用HTML、CSS和JavaScript实现一个简单的图片轮播效果。HTML部分定义轮播容器和图片,CSS负责样式和过渡效果,JavaScript处理逻辑。 <div cl…

vue实现点选效果

vue实现点选效果

实现点选效果的基本思路 在Vue中实现点选效果通常涉及监听用户的点击事件,并通过动态绑定类名或样式来改变元素的外观。核心是利用Vue的响应式数据和事件绑定机制。 使用v-bind和v-on实现 通过…

js实现图片的拖动

js实现图片的拖动

实现图片拖动的步骤 HTML 结构 在 HTML 中创建一个可拖动的图片元素,确保设置 draggable 属性为 true。 <img id="draggable-img" src="ima…

vue实现检索效果

vue实现检索效果

Vue实现检索功能的方法 在Vue中实现检索功能通常需要结合数据绑定、计算属性和方法。以下是几种常见的实现方式: 基础实现(基于计算属性) <template> <div>…

vue实现加载图片

vue实现加载图片

Vue 实现图片加载的方法 在 Vue 中加载图片可以通过多种方式实现,以下是一些常见的方法: 使用静态资源路径 将图片放在 public 或 assets 目录下,通过相对路径或绝对路径引用。…