仿小米官網輪播圖(Banner)的實現

LQ-劉強發表於2018-03-26

本篇是仿照小米官網所做的輪播圖,注意事項(圖片命名規則為 banner-img-0.jpg,banner-img-1.jpg 依此類推);


例項程式碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

        #banner{
            margin: 100px auto;
            position: relative;
            width: 813px;
            height: 320px;
        }

        #banner>img{
            height: 100%;
            width: 100%;
            cursor: pointer;
        }

        #banner>div{
            position: absolute;
            bottom: 20px;
            right: 20px;
        }

        #banner>div>span{
            display: block;
            width: 10px;
            height: 10px;
            float: left;
            border: #333333 solid 2px;
            border-radius: 50%;
            background-color: #717987;
            margin-left: 10px;
            cursor: pointer;
        }

        #banner>div>span:first-child{
            background-color: white;
        }

    </style>
</head>
<body>

<div id="banner">
    <img src="img/banner-img-0.jpg"/>
    <div>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
    </div>
</div>

<script type="text/javascript" src="js/jquery-1.12.3.js" ></script>
<script type="text/javascript">

    let $bannerImg = $("#banner").children("img");
    let $bannerPoints = $("#banner>div");
    let prePoint = 0;//記錄上一個被點選的小點
    $bannerPoints.delegate("span", "click mouseenter", function () {
        clearInterval(bannerInterval);//每次點選時,先停止輪播
        let $2 = $(this);
        if (prePoint !== $2.index()) { //防止滑鼠移入時 使用者點選了 重複兩次走相同的邏輯賦值
            currentPoint = $2.index();//賦值-- 關聯到圖片的迴圈設定
            $2.css("background-color", "white").parent().children(":eq(" + prePoint + ")").css("background-color", "#717987");
            $bannerImg.attr("src", "img/banner-img-" + $2.index() + ".jpg");
            prePoint = $2.index(); //記錄上一個點選的小點
        }
    });
    $bannerPoints.delegate("span", "mouseleave", function () { //滑鼠離開時 繼續輪播
        startBannerInterval();
    });
    let bannerInterval;
    let currentPoint = 0;
    let pointSize = $bannerPoints.children().length - 1;//用來重置小點的判斷
    function startBannerInterval() {
        let children = $bannerPoints.find("span");
        bannerInterval = setInterval(function () {
            children.eq(prePoint).css("background-color", "#717987");
            prePoint = currentPoint; //賦值-- 關聯到圖片的迴圈設定
            if (currentPoint > pointSize) {
                currentPoint = 0;
                prePoint = 0;
            }
            children.eq(currentPoint).css("background-color", "white");
            $bannerImg.attr("src", "img/banner-img-" + currentPoint + ".jpg");
            currentPoint++;
        }, 2000);
    }
    startBannerInterval();//開始輪播

</script>

</body>
</html>


相關文章