.scroll-box {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
}
.scroll-content {
  position: absolute;
  top: 0;
  left: 0;
  white-space: nowrap;
  transition: transform 0.5s ease-in-out;
}
.scroll-content img {
  display: inline-block;
  width: 20%;
  height: 100%;
  object-fit: cover;
}
.scroll-arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 30px;
  height: 30px;
  background: #fff;
  border-radius: 50%;
  cursor: pointer;
}
.left-arrow {
  left: 10px;
}
.right-arrow {
  right: 10px;
}
new Vue({
  el: '#app',
  data: {
    currentIndex: 0,
    total: 5,
    contentWidth: 0,
    itemWidth: 0,
  },
  mounted() {
    this.contentWidth = this.$refs.content.offsetWidth;
    this.itemWidth = this.contentWidth / 5;
  },
  methods: {
    scroll(direction) {
      this.currentIndex += direction;
      if (this.currentIndex < 0) {
        this.currentIndex = 0;
      }
      if (this.currentIndex >= this.total - 5) {
        this.currentIndex = this.total - 5;
      }
      this.$refs.content.style.transform = `translateX(-${this.currentIndex * this.itemWidth}px)`;
    }
  }
})

代码解析:

  1. HTML 结构:
  • scroll-box 是一个容器,设置 overflow: hidden 来隐藏超出部分,保证滚动效果。
  • scroll-content 是图片内容的容器,使用 white-space: nowraptransform 实现图片的横向排列和滚动。
  • scroll-arrow 是左右箭头,通过 @click 事件触发滚动函数。
  1. CSS 样式:
  • 调整容器和图片容器的大小和位置。
  • 设定图片宽度为容器的 20%,使用 object-fit: cover 保证图片填充容器。
  • 设定箭头的大小、颜色和位置。
  1. JavaScript 逻辑:
  • 使用 Vue 框架,在 mounted 生命周期钩子中获取图片容器和图片的宽度。
  • 使用 currentIndex 记录当前显示的图片索引。
  • scroll 函数通过改变 currentIndextransform 属性实现图片的横向滚动。
  • 设置边界条件,防止 currentIndex 超出图片数量范围。

总结:

通过 Vue、CSS 和 JavaScript 的协作,我们可以轻松实现一个简洁的图片横向滚动组件。你可以根据自己的需求调整图片数量、宽度、箭头样式等细节,打造出个性化的效果。

Vue 图片横向滚动代码实现:简单易懂的教程

原文地址: https://www.cveoy.top/t/topic/lAys 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录