关于前端:使用js和csstransition属性57行代码实现简易无缝轮播图

30次阅读

共计 1159 个字符,预计需要花费 3 分钟才能阅读完成。

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div img {
            position: absolute;
            width: 100%;
            height: 200px;
            transition: all;
            transition-duration: 0.5s;
        }

        .carousel {position: relative;}
    </style>
</head>

<body>
    <div class="carousel">
        <img src="./imgs/1.jpeg" alt=""id="1">
        <img src="./imgs/2.jpeg" alt=""id="2">
        <img src="./imgs/3.jpeg" alt=""id="3">
    </div>
    <script>
        window.onload = function () {let img1 = document.getElementById("1")
            let img2 = document.getElementById("2")
            let img3 = document.getElementById("3")
            let img_box = document.getElementsByTagName("div","tag")[0]
            console.log(img_box)
            let img_list = [img1,img2,img3]
            img_list[0].style.left = "340px"
            img_list[1].style.left = "-200px"
            img_list[2].style.left = "0px"
                setInterval(() => {img_list[0].style.left = "680px"
                    img_list[2].style.left = "340px"
                    img_list[1].style.left = "0px"
                    img_list[0].style.display = "none"
                    img_list[0].style.left = "-340px"
                    setTimeout(()=>{img_list[0].style.display = ""
                        img_list.unshift(img_list.pop())
                    },450)
                }, 3000)
        }

    </script>
</body>

</html>

外围是保护一个队列和相对定位的个性。通过调整 left 的宽度实现轮播。本轮播图没有对响应性进行适配,最佳宽度是 356px。

正文完
 0