轮播图的五种写法(原生、vue2、vue3、react类组件,react函数组件)

轮播图效果是一种在网页或应用程序中展示多张图片或内容的方式,通常以水平或垂直的方式循环播放。本文使用原生、vue2、vue3、react类组件,react函数组件五种写法实现了简单的轮播图效果,需要更多轮播效果需要再增加样式或者动画。

  1. 淡入淡出效果:每张图片渐渐淡入显示,然后渐渐淡出消失,过渡效果平滑。(使用CSS的@keyframesanimation属性)

    创建一个@keyframes,定义两个关键帧,一个是初始状态,一个是结束状态,其中透明度从0到1,将该动画应用到需要淡入淡出的元素上,使用animation属性指定动画名称、持续时间、动画效果等。

  2. 平移效果:每张图片从一侧平滑地移动到另一侧,形成连续的平移效果。(使用CSS的transformtransition属性)

    使用transform: translate(x, y);来实现平移效果,其中xy是水平和垂直方向上的平移距离。可以使用负值来实现反方向的平移。添加过渡效果来使平移更加平滑。使用transition: transform duration;来设置过渡效果的持续时间

  3. 缩放效果:每张图片从小到大或从大到小进行缩放,给人一种逐渐放大或缩小的感觉。(使用CSS的transform属性和scale()

  4. 旋转效果:每张图片围绕中心点进行旋转,形成连续的旋转效果。(使用CSS的transform属性和rotate()

实现轮播图的基本步骤:

  1. 创建一个包含轮播图图片的HTML结构,可以使用<ul><li>标签来创建一个图片列表。

  2. 使用CSS样式设置轮播图容器的宽度和高度,以及图片列表的宽度和高度,并设置overflow: hidden来隐藏超出容器范围的图片。

  3. 使用JavaScript获取轮播图容器和图片列表,并设置初始的索引值为0。

  4. 创建一个函数来切换图片,可以通过改变图片列表的left属性值来实现。可以使用transform属性或marginLeft属性来实现图片的平滑过渡。

  5. 创建一个定时器来自动切换图片,可以使用setInterval函数来设置定时器,每隔一段时间调用切换图片的函数。

  6. 监听轮播图容器的鼠标移入和移出事件,当鼠标移入时清除定时器,当鼠标移出时重新设置定时器。

  7. 监听轮播图容器的左右箭头点击事件,分别调用切换图片的函数来切换到上一张或下一张图片。

  8. 可以根据需要添加其他功能,比如添加指示器来显示当前图片的索引,点击指示器可以切换到对应的图片。

1. 使用原生js实现轮播图

HTML:

html 复制代码
<div class="carousel">
  <div class="slides">
    <img src="image1.jpg" alt="Image 1">
    <img src="image2.jpg" alt="Image 2">
    <img src="image3.jpg" alt="Image 3">
  </div>
  <button class="prev">Previous</button>
  <button class="next">Next</button>
</div>

CSS:

css 复制代码
.carousel {
  position: relative;
  width: 500px;
  height: 300px;
  overflow: hidden;
}

.slides {
  display: flex;
  transition: transform 0.5s ease-in-out;
}

.slides img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.prev,
.next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  padding: 10px;
  background-color: lightgray;
  border: none;
  cursor: pointer;
}

.prev {
  left: 10px;
}

.next {
  right: 10px;
}

JavaScript:

javascript 复制代码
const carousel = document.querySelector('.carousel');
const slides = carousel.querySelector('.slides');
const prevButton = carousel.querySelector('.prev');
const nextButton = carousel.querySelector('.next');
const slideWidth = carousel.offsetWidth;

let slideIndex = 0;

prevButton.addEventListener('click', () => {
  slideIndex--;
  if (slideIndex < 0) {
    slideIndex = slides.childElementCount - 1;
  }
  updateSlidePosition();
});

nextButton.addEventListener('click', () => {
  slideIndex++;
  if (slideIndex >= slides.childElementCount) {
    slideIndex = 0;
  }
  updateSlidePosition();
});

function updateSlidePosition() {
  slides.style.transform = `translateX(${-slideIndex * slideWidth}px)`;
}

2. 使用vue2实现轮播图

vue 复制代码
<template>
  <div class="carousel">
    <div class="slide" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
      <div v-for="(item, index) in items" :key="index" class="item">
        <img :src="item.image" alt="carousel image">
      </div>
    </div>
    <div class="dots">
      <span v-for="(item, index) in items" :key="index" :class="{ active: index === currentIndex }" @click="goToSlide(index)"></span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentIndex: 0,
      items: [
        { image: 'image1.jpg' },
        { image: 'image2.jpg' },
        { image: 'image3.jpg' },
      ],
    };
  },
  methods: {
    goToSlide(index) {
      this.currentIndex = index;
    },
  },
};
</script>

<style scoped>
.carousel {
  width: 100%;
  overflow: hidden;
}

.slide {
  display: flex;
  transition: transform 0.5s ease-in-out;
}

.item {
  flex: 0 0 100%;
}

.dots {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.dots span {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: gray;
  margin: 0 5px;
  cursor: pointer;
}

.dots span.active {
  background-color: black;
}
</style>

3. 使用vue3实现轮播图

在Vue3中实现轮播图可以使用<transition>组件和ref来实现。

  1. 在组件中引入所需的图片和样式:
html 复制代码
<template>
  <div class="carousel">
    <transition name="slide">
      <img :src="currentImage" :key="currentImage" class="image" />
    </transition>
    <button @click="prevImage" class="prev">上一张</button>
    <button @click="nextImage" class="next">下一张</button>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const images = [
      'image1.jpg',
      'image2.jpg',
      'image3.jpg',
      'image4.jpg'
    ];

    const currentIndex = ref(0);

    const prevImage = () => {
      currentIndex.value = (currentIndex.value - 1 + images.length) % images.length;
    };

    const nextImage = () => {
      currentIndex.value = (currentIndex.value + 1) % images.length;
    };

    const currentImage = computed(() => {
      return images[currentIndex.value];
    });

    return {
      currentImage,
      prevImage,
      nextImage
    };
  }
};
</script>

<style>
.carousel {
  position: relative;
}

.image {
  width: 100%;
  height: auto;
}

.slide-enter-active,
.slide-leave-active {
  transition: transform 0.5s;
}

.slide-enter,
.slide-leave-to {
  transform: translateX(100%);
}

.prev,
.next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  padding: 10px;
  background-color: #333;
  color: #fff;
  border: none;
  cursor: pointer;
}

.prev {
  left: 10px;
}

.next {
  right: 10px;
}
</style>

使用ref创建了一个currentIndex变量来追踪当前显示的图片索引。然后,在prevImagenextImage方法中更新currentIndex来切换图片。最后,使用<transition>组件来给图片添加过渡效果,并使用computed属性来获取当前显示的图片路径。

4. 使用react类组件实现轮播图

jsx 复制代码
import React, { Component } from "react";

class Carousel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      images: [
        "image1.jpg",
        "image2.jpg",
        "image3.jpg",
        "image4.jpg"
      ],
      currentIndex: 0
    };
  }

  componentDidMount() {
    this.startCarousel();
  }

  componentWillUnmount() {
    this.stopCarousel();
  }

  startCarousel = () => {
    this.carouselInterval = setInterval(() => {
      this.setState(prevState => ({
        currentIndex: (prevState.currentIndex + 1) % prevState.images.length
      }));
    }, 2000);
  };

  stopCarousel = () => {
    clearInterval(this.carouselInterval);
  };

  render() {
    const { images, currentIndex } = this.state;
    return (
      <div className="carousel">
        <img src={images[currentIndex]} alt="carousel" />
      </div>
    );
  }
}

export default Carousel;

使用constructor初始化了images数组和currentIndex状态。componentDidMount生命周期方法用于在组件挂载后启动轮播。startCarousel方法使用setInterval来每隔2秒更新currentIndex状态,实现轮播的效果。componentWillUnmount生命周期方法用于在组件卸载前停止轮播。最后,render方法根据currentIndex状态来渲染当前轮播图的图片。

5.使用react函数组件实现轮播图

jsx 复制代码
import React, { useState } from 'react';

const Carousel = ({ images }) => {
  const [currentIndex, setCurrentIndex] = useState(0);

  const goToPrevSlide = () => {
    setCurrentIndex((prevIndex) => (prevIndex === 0 ? images.length - 1 : prevIndex - 1));
  };

  const goToNextSlide = () => {
    setCurrentIndex((prevIndex) => (prevIndex === images.length - 1 ? 0 : prevIndex + 1));
  };

  return (
    <div className="carousel">
      <button onClick={goToPrevSlide}>Prev</button>
      <img src={images[currentIndex]} alt="carousel-slide" />
      <button onClick={goToNextSlide}>Next</button>
    </div>
  );
};

export default Carousel;

使用useState钩子来管理当前轮播图的索引。通过goToPrevSlide和goToNextSlide函数,可以更新当前索引以显示前一个或下一个轮播图。

在父组件中,传递一个包含所有轮播图图片URL的数组作为images属性,通过将images数组传递给Carousel组件,可以在轮播图中显示这些图片。

jsx 复制代码
import React from 'react';
import Carousel from './Carousel';

const App = () => {
  const images = [
    'https://example.com/image1.jpg',
    'https://example.com/image2.jpg',
    'https://example.com/image3.jpg',
  ];

  return (
    <div>
      <h1>Carousel Example</h1>
      <Carousel images={images} />
    </div>
  );
};

export default App;
相关推荐
Boilermaker19924 分钟前
【Java EE】SpringIoC
前端·数据库·spring
中微子15 分钟前
JavaScript 防抖与节流:从原理到实践的完整指南
前端·javascript
天天向上102430 分钟前
Vue 配置打包后可编辑的变量
前端·javascript·vue.js
芬兰y1 小时前
VUE 带有搜索功能的穿梭框(简单demo)
前端·javascript·vue.js
好果不榨汁1 小时前
qiankun 路由选择不同模式如何书写不同的配置
前端·vue.js
小蜜蜂dry1 小时前
Fetch 笔记
前端·javascript
拾光拾趣录1 小时前
列表分页中的快速翻页竞态问题
前端·javascript
小old弟1 小时前
vue3,你看setup设计详解,也是个人才
前端
Lefan1 小时前
一文了解什么是Dart
前端·flutter·dart
Patrick_Wilson1 小时前
青苔漫染待客迟
前端·设计模式·架构