JavaScript實現簡單的圖片切換功能


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>圖片切換</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            width: 200px;
            height: 300px;
            margin: 50px auto;
            padding: 20px;
            background-color: skyblue;
            text-align: center;
        }
        img{
            width: 200px;
            height: 200px;
            margin: 20px 0;
        }
    </style>
    <script>
        // 存儲照片地址的數組
        let imgArr = ["https://images.cnblogs.com/cnblogs_com/TomHe789/1693260/o_200409051704animal1.png", "https://images.cnblogs.com/cnblogs_com/TomHe789/1693260/o_200409051711animal2.png", "https://images.cnblogs.com/cnblogs_com/TomHe789/1693260/o_200409051717animal3.png", "https://images.cnblogs.com/cnblogs_com/TomHe789/1693260/o_200409051722animal4.png", "https://images.cnblogs.com/cnblogs_com/TomHe789/1693260/o_200409051726animal5.png"];

        // 照片的索引
        let index = 0;
        window.onload = function() {
            let oP = document.getElementsByTagName("p")[0];
            oP.innerHTML = "一共有" + imgArr.length + "張照片,這是第" + (index+1) +"張";

            let oImg = document.getElementsByTagName("img")[0];
            let oPrev = document.getElementsByClassName("prev")[0];
            let oNext = document.getElementsByClassName("next")[0];

            // 點擊上一張響應事件
            oPrev.onclick = function () {
                index--;
                //實現照片循環
                if (index < 0) {
                    index = imgArr.length-1;
                }
                oP.innerHTML = "一共有" + imgArr.length + "張照片,這是第" + (index+1) +"張";
                oImg.src = imgArr[index];

            };

            // 點擊下一張響應事件
            oNext.onclick = function () {
                index++;
                //實現照片循環
                if (index >= imgArr.length) {
                    index = 0;
                }
                oP.innerHTML = "一共有" + imgArr.length + "張照片,這是第" + (index+1) +"張";
                oImg.src = imgArr[index];
            };
        };
    </script>
</head>
<body>
    <div class="box">
        <p></p>
        <img src="../../images/animal1.png" alt="">
        <button class="prev">上一張</button>
        <button class="next">下一張</button>
    </div>
</body>
</html>

最終的效果
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM