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>

運行效果

點擊屏幕左側、右側圖片進行切換
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章