蝙蝠岛资源网 Design By www.hbtsch.com

代码如下所示:

<!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="/UploadFiles/2021-04-02/animal1.png">

最终的效果

JavaScript实现简单的图片切换功能(实例代码)

总结

标签:
js,图片切换,js,图片切换功能

蝙蝠岛资源网 Design By www.hbtsch.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
蝙蝠岛资源网 Design By www.hbtsch.com

评论“JavaScript实现简单的图片切换功能(实例代码)”

暂无JavaScript实现简单的图片切换功能(实例代码)的评论...