轮播图的五种写法(原生、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结构,可以使用

    • 标签来创建一个图片列表。

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

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

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

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

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

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

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

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

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">Previousbutton>
  <button class="next">Nextbutton>
div>

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:

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实现轮播图






3. 使用vue3实现轮播图

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

  1. 在组件中引入所需的图片和样式:
<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来切换图片。最后,使用组件来给图片添加过渡效果,并使用computed属性来获取当前显示的图片路径。

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

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 (
      
carousel
); } } export default Carousel;

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

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

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 (
    
carousel-slide
); }; export default Carousel;

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

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

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 (
    

Carousel Example

); }; export default App;

你可能感兴趣的:(react.js,前端,前端框架)