jQuery实现简易轮播图

要求

点击页面的左边, 展示左边的一张图片
点击页面的右边, 展示右边的一张图片
越界循环

知识点

  1. $(window).width() 获取屏幕宽度
  2. animation动画
  3. clone()克隆结点
  4. append、prepend插入结点

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{
            margin: 0;
            padding: 0;
            list-style: none;
        }

        .box{
            width: 520px;
            height: 280px;
            margin: 100px auto;
            border: 1px solid orangered;
            overflow: hidden;
        }

        .box>ul{
            position: relative;
        }

        .box>ul>li{
            position: absolute;
            left: 0;
            top: 0;
        }

        .box>ul>li>img{
            width: 520px;
            height: 280px;
        }
    </style>
</head>
<body>
   <div class="box">
       <ul>
           <li><img src="images/01.jpg" alt=""></li>
       </ul>
   </div>

<script type="text/javascript" src="lib/jquery-3.3.1.js"></script>
<script type="text/javascript">
   $(function () {
      /*
        要求:
        点击页面的左边, 展示左边的一张图片
        点击页面的右边, 展示右边的一张图片
        越界循环
      */
      // 1. 准备数据源
      var imageNames = [];
      for(var i=1; i<5; i++){
          imageNames.push('images/0'+ i +'.jpg');
      }
      // console.log(imageNames);

      // 2. 设置当前的索引
      var currentShowImgIndex = 0;

      // 3. 监听点击
       $(document).click(function (event) {
            // 3.1 定义变量
            var middleX = $(window).width() * 0.5;
            var isLeft = false;

            // 3.2 判断
            if(event.pageX <= middleX){ // 左边
                isLeft = true;
                currentShowImgIndex = (currentShowImgIndex - 1 + imageNames.length) % imageNames.length;
            }else { // 右边
                isLeft = false;
                currentShowImgIndex = (currentShowImgIndex + 1) % imageNames.length;
            }
           // console.log(currentShowImgIndex);

           // 3.3 创建节点, 放在ul的最前面
           var imageName = imageNames[currentShowImgIndex];
           var $newTag = $('.box>ul>li').clone();
           $newTag.children('img').attr('src', imageName);
           $('.box>ul').prepend($newTag);

           // 3.4 动画展示和删除
           if(isLeft){
               $('.box>ul>li:last').animate({
                   left: '-520px'
               }, 200, function () {
                   $(this).remove();
               })
           }else {
               $('.box>ul>li:last').animate({
                   left: '520px'
               }, 200, function () {
                   $(this).remove();
               })
           }
       });


   });
</script>
</body>
</html>

运行效果

点击屏幕左侧、右侧图片进行切换
在这里插入图片描述
在这里插入图片描述

发布了270 篇原创文章 · 获赞 123 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/KaiSarH/article/details/104597531