原生轮播图的实现

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>轮播图title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .slideshow-container {
            width: 500px;
            height: 500px;
            overflow: hidden;
            position: relative;
            margin: 0 auto;
            background-image: linear-gradient(to top, #fad0c4 0%, #fad0c4 1%, #ffd1ff 100%);
        }

        .slide {
            /* 等比例缩小图片 */
            background-size: cover;
            /* 图片不重复 */
            background-repeat: no-repeat;
            position: absolute;
            /* 初始状态下图片不显示 */
            opacity: 0;
            /* 让图片淡入淡出 */
            transition: opacity 0.75s ease-in-out;
            /* 让图片垂直居中 */
            top: 50%;
            transform: translateY(-50%);
        }

        /* 让第一张图片显示出来 */
        .fade {
            opacity: 1;
        }

        .slide img {
            width: 100%;
            height: 100%;
        }
    style>
head>

<body>
    <div class="slideshow-container">
        <div class="slide fade">
            <img src="img/1.png" alt="silde1">
        div>
        <div class="slide">
            <img src="img/2.png" alt="silde2">
        div>
        <div class="slide">
            <img src="img/3.jpg" alt="silde3">
        div>
    div>
    <script>
        var slides = document.querySelectorAll('.slide');
        var currentSlide = 0;
        // 设置定时器
        var slideInterval = setInterval(nextSlide, 2000);

        function nextSlide() {
            // 将当前图片的class设置为slide
            slides[currentSlide].className = 'slide';
            // 获取下一张图片的索引
            currentSlide = (currentSlide + 1) % slides.length;
            // 将下一张图片的class设置为slide fade
            slides[currentSlide].className = 'slide fade';
        }
    script>
body>

html>

你可能感兴趣的:(项目实践,前端,轮播图)