美文网首页
JS 图片轮播练手

JS 图片轮播练手

作者: 醉叶惜秋 | 来源:发表于2018-08-10 09:35 被阅读19次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>上下切换图片</title>
    </head>
    <body>
    
     <img name = 'icon' src="images/IMG_2931.JPG">
    <p></p>
    <button>上一张</button>
    <button>下一张</button>
    
     <script>
         //1.全局变量
         var maxIndex = 2934;
         var minIndex = 2931;
         var currentIndex = minIndex;
         //2. 拿到需要操作的标签
         var img = document.getElementsByName('icon')[0];
    
         var pre = document.getElementsByTagName('button')[0];
    
         var next = document.getElementsByTagName('button')[1];
    
         //3.监听按钮的点击
         //3.1 上一张
         pre.onclick = function () {
             if (currentIndex == minIndex){
                 currentIndex = maxIndex;
             } else{
                 currentIndex -= 1;
             }
             //改变图片
             img.src = 'images/IMG_' + currentIndex + '.JPG';
         }
         //3.2 下一张
         next.onclick = function () {
             if (currentIndex == maxIndex){
                 currentIndex = minIndex;
             } else{
                 currentIndex += 1;
             }
             //改变图片
             img.src = 'images/IMG_' + currentIndex + '.JPG';
         }
    
     </script>
    
    
    </body>
    </html>
    
    image.png

    相关文章

      网友评论

          本文标题:JS 图片轮播练手

          本文链接:https://www.haomeiwen.com/subject/dtahbftx.html