實戰電商頁面2:幻燈片

尹成發表於2018-11-14

在上一篇部落格中我們實現了電商頁面的搭建和樣式的調整,這裡我們將使用jQuery實現頁面中部的幻燈片效果,我們可以點選左右按鈕來切換圖片,如果沒有點選左右按鈕,圖片自動向左切換。
效果圖:
這裡寫圖片描述

$(function () {

    /*定義上一張頁碼,下一張頁碼*/
    var previous = 0;
    var current = 0;
    var direction = "left";
    var $timer;

    /*預設顯示第一張圖片,其餘圖片在右側蹲著待命*/
    var $ul = $(".gallery ul.sliders")
    var $lis = $ul.children("li");
    var len = $lis.length;
    $lis.each(function () {
        if ($(this).index() == 0) {
            $(this).css({left: 0});
        } else {
            $(this).css({left: 760});
        }
    });

    /*在dots中動態新增一堆點*/
    var $dots = $(".dots");
    for (var i = 0; i < len; i++) {
        $dots.append($("<li></li>"));
    }
    $dots = $dots.children("li")
    $dots.eq(current).addClass("active").siblings().removeClass("active");

    /*定義prev,next的點選監聽*/
    var $btnPrev = $(".prev");
    var $btnNext = $(".next");
    $btnPrev.click(function () {
        previous = current;
        current--;
        direction = "right";
        if (current < 0) {
            current = len - 1;
        }
        console.log("previous=" + previous + ",current=" + current + ",direction=" + ">");
        scroll(previous, current, "right");
    });

    $btnNext.click(function () {
        previous = current;
        current++;
        direction = "left";
        if (current > len - 1) {
            current = 0;
        }
        console.log("previous=" + previous + ",current=" + current + ",direction=" + "<");
        scroll(previous, current, "left");
    });

    /*定義指示器的點選監聽*/
    $dots.click(function () {
        previous = current;
        current = $(this).index();
        if (previous > current) {
            direction = "right";
        } else {
            direction = "left";
        }
        scroll(previous, current, direction);
    })

    /*自動播放*/
    $timer = setInterval(function () {
        $btnNext.trigger("click");
    }, 3000);

    /*滑鼠覆蓋時停止自動播放,移出時恢復*/
    $ul.hover(
        function () {
            clearInterval($timer);
        }, function () {
            $timer = setInterval(function () {
                $btnNext.trigger("click");
            }, 3000);
        }
    )

    /*滾動函式*/
    function scroll(previous, current, direction) {

        /*啟用指示器*/
        $dots.eq(current).addClass("active").siblings().removeClass("active");

        /*找到要滑入滑出的元素*/
        previous = $lis.eq(previous);
        current = $lis.eq(current);

        /*提前把要滑入的li放在預備位置上*/
        if (direction == "left") {
            current.css({left: 760});
        } else {
            current.css({left: -760});
        }

        /*滑入當前張,滑出上一張*/
        current.animate({left: 0});
        if (direction == "left") {
            previous.animate({left: -760});
        } else {
            previous.animate({left: 760});
        }

    }

})

學院Go語言視訊主頁
https://edu.csdn.net/lecturer/1928

清華團隊帶你實戰區塊鏈開發
掃碼獲取海量視訊及原始碼 QQ群:721929980
在這裡插入圖片描述

相關文章