javaScript 手写图片轮播

时间:2024-01-19 11:57:38
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>js图片轮播切换</title>
  6. <style type="text/css">
  7.   .imgCon{width: 400px;height: 400px;border: 2px solid #DCDCDC;margin: 100px auto;position: relative;}
  8.   .imgCon span{display: block;position: absolute;left: 0px;width: 100%;height: 30px;background: #808080;text-align: center;font-size: 18px;line-height: 30px;}
  9.   .numStyle{top: 0px;}
  10.   .textStyle{bottom: 0px;}
  11.   .imgCon strong{font-size: 30px;color: #000000;position: absolute;top: 50%;display: block;background: gray;cursor: pointer;}
  12.   .imgCon .prev{left: 10px;}
  13.   .imgCon .next{left: 370px;}
  14.   img{width:400px;height: 400px;}
  15. </style>
  16. </head>
  17. <body>
  18.   <div class="imgCon">
  19.     <span id="numCon" class="numStyle">加载中...</span>
  20.     <span id="textCon" class="textStyle">加载中...</span>
  21.     <strong id="prev" class="prev">&lt;</strong>
  22.     <strong id="next" class="next">&gt;</strong>
  23.     <img src="" id="imgChange"/>
  24.   </div>
  25.   <script type="text/javascript">
  26.     var numCon = document.getElementById('numCon');
  27.     var textCon = document.getElementById('textCon');
  28.     var prev = document.getElementById('prev');
  29.     var next = document.getElementById('next');
  30.     var imgChange = document.getElementById('imgChange');
  31.     var imgArr = ['img/ad1.jpg','img/ad2.jpg','img/ad3.jpg','img/ad4.jpg'];
  32.     var imgText = ['第一张','第二张','第三张','第四张'];
  33.     var num = 0;
  34.     //数字 图片变化函数
  35.     function imgTab(){
  36.       numCon.innerHTML = num+1 + '/' + imgArr.length; //数字变化
  37.       textCon.innerHTML = imgText[num]; //底部文字内容变化
  38.       imgChange.src = imgArr[num]; //图片变化
  39.     }
  40.     imgTab();
  41.     //下一张 按钮
  42.     next.onclick = function(){
  43.     num++;
  44.     if(num == imgArr.length){
  45.       num = 0;
  46.     }
  47.     imgTab();
  48.     }
  49.     //上一张 按钮
  50.     prev.onclick = function(){
  51.       num--;
  52.     if(num == -1){
  53.       num = imgArr.length-1;
  54.     }
  55.     imgTab();
  56.     }
  57.   </script>
  58. </body>
  59. </html>