1. 程式人生 > >JQ輪播圖(多張同時顯示)

JQ輪播圖(多張同時顯示)

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
    <script type="text/javascript" src="js/test.js"></script>
    <link rel="stylesheet" type="text/css" href="css/test.css" />
</head>
<body>
    <div id="carousel" class="clearfix"></div>
</body>
</html>

CSS:

*{
    display: block;
    margin: 0px;
    border: 0px;
}
.clearfix:after{
    display: block;
    content:'';
    clear: both;
    height:0;
}
#carousel{
    width: 1224px;
    height: 144px;
    margin: 50px auto;
    position: relative;
}
#carousel>img{
    cursor: pointer;
    width: 256px;
    height: 144px;
    float: left;
    margin: 0 20px;
}
#previous,#next{
    float: left;
    line-height: 50px;
    margin-top: 47px;
    font-size: 25px;
    cursor: pointer;
}

JQ:

$(function(){
    $("#carousel").append("<div id=\"previous\"><</div>");
    for(var j=0;j<4;j++)
        $("#carousel").append("<img src=\"img/"+(j+1)+".jpg\"/>");
    $("#carousel").append("<div id=\"next\">></div>");
    var i=0;
    var index=i;
    function start () {
        i=i%5;
        index=i;
        change();
        i++;
    }
    function change(){
        for(var j=0;j<4;j++)
            $("#carousel>img").eq(j).attr("src","img/"+((i+j)%5+1)+".jpg");
        $("#dots>div").css("background","rgba(255,255,255,0.6)");
        $("#dots>div").eq(i).css("background","rgba(255,0,0,0.6)");
    }
    var time=setInterval(start,3000);
    $("#carousel>img").hover(function() {
        clearInterval(time);
    },function () {
        time=setInterval(start,3000);
    });
    $("#previous").click(function () {
        clearInterval(time);
        index++;
        i=index%5;
        change();
        time=setInterval(start,3000);
    });
    $("#next").click(function () {
        clearInterval(time);
        index--;
        if(index<0)
            index=4;
        i=index;
        change();
        time=setInterval(start,3000);
    });
});