轮播图的五种写法(原生、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;
相关推荐
甜兒.30 分钟前
鸿蒙小技巧
前端·华为·typescript·harmonyos
Jiaberrr4 小时前
前端实战:使用JS和Canvas实现运算图形验证码(uniapp、微信小程序同样可用)
前端·javascript·vue.js·微信小程序·uni-app
everyStudy4 小时前
JS中判断字符串中是否包含指定字符
开发语言·前端·javascript
城南云小白4 小时前
web基础+http协议+httpd详细配置
前端·网络协议·http
前端小趴菜、4 小时前
Web Worker 简单使用
前端
web_learning_3214 小时前
信息收集常用指令
前端·搜索引擎
tabzzz5 小时前
Webpack 概念速通:从入门到掌握构建工具的精髓
前端·webpack
200不是二百5 小时前
Vuex详解
前端·javascript·vue.js
滔滔不绝tao5 小时前
自动化测试常用函数
前端·css·html5
码爸5 小时前
flink doris批量sink
java·前端·flink