Vue 图片轮播:5张图片横向移动代码示例
以下是一份用 Vue 和 CSS 实现 5 个图片横向移动的代码示例:
HTML 模板:
<template>
<div class='carousel'>
<div class='carousel-wrapper' :style="{ transform: `translateX(${offset}px)` }">
<div class='carousel-item' v-for='(item, index) in items' :key='index'>
<img :src='item.src' alt=''>
</div>
</div>
<button class='carousel-btn' @click='move(-1)'><</button>
<button class='carousel-btn' @click='move(1)'>></button>
</div>
</template>
CSS 样式:
.carousel {
position: relative;
overflow: hidden;
}
.carousel-wrapper {
display: flex;
transition: transform 0.5s ease-in-out;
}
.carousel-item {
flex: 0 0 auto;
margin-right: 20px;
}
.carousel-item img {
width: 100%;
height: auto;
}
.carousel-btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 40px;
height: 40px;
border: none;
background-color: rgba(0,0,0,0.5);
color: #fff;
font-size: 24px;
text-align: center;
line-height: 40px;
cursor: pointer;
}
.carousel-btn:first-of-type {
left: 0;
}
.carousel-btn:last-of-type {
right: 0;
}
JS 代码:
export default {
data() {
return {
items: [
{ src: 'path/to/image1.jpg' },
{ src: 'path/to/image2.jpg' },
{ src: 'path/to/image3.jpg' },
{ src: 'path/to/image4.jpg' },
{ src: 'path/to/image5.jpg' },
],
offset: 0,
itemWidth: 0,
}
},
mounted() {
this.itemWidth = this.$refs.carouselItem[0].clientWidth;
},
methods: {
move(direction) {
const maxOffset = (this.items.length - 1) * this.itemWidth;
this.offset = Math.min(Math.max(this.offset + direction * this.itemWidth, 0), maxOffset);
}
}
}
解释:
- HTML 模板中,使用 Flex 布局实现图片横向排列,并使用 Vue 的响应式数据绑定控制图片组件的显示。
- CSS 样式中,定义了轮播图容器、图片容器、图片、按钮等元素的样式,并使用绝对定位实现了左右切换按钮。
- JS 代码中,定义了图片组件的数据和方法,其中 mounted 生命周期钩子函数用于获取图片组件的宽度,move 方法用于实现图片的横向移动,通过计算 offset 值实现。
原文地址: https://www.cveoy.top/t/topic/lAyG 著作权归作者所有。请勿转载和采集!