1. 程式人生 > >簡單的輪播圖(單張顯示,無特效)

簡單的輪播圖(單張顯示,無特效)

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">
        <img src="img/1.jpg"/>
        <div id="dots">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
        <div id="previous"><</div>
        <div id="next">></div>
    </div>
</body>
</html>

CSS:

*{
    display: block;
    margin: 0px;
    border: 0px;
}
#carousel,#carousel>img{
    width: 1024px;
    height: 576px;
}
#carousel{
    margin: 50px auto;
    position: relative;
}
#carousel>img{
    cursor: pointer;
    position: absolute;
    left: 0px;
    top: 0px;
}
#carousel>img:first-child{
    display: block;
}
#dots{
    position: absolute;
    left: 362px;
    bottom: 0px;
    background-color: rgba(0,0,0,0.6);
}
#dots>div{
    float: left;
    width: 20px;
    height: 20px;
    border-radius: 10px;
    margin: 5px 20px;
    cursor: pointer;
    background-color: rgba(255,255,255,0.6);
}
#dots>div:first-child{
    background-color: rgba(255,0,0,0.6);
}
#previous,#next{
    text-align: center;
    position: absolute;
    width: 30px;
    line-height: 50px;
    top: 273px;
    font-size: 25px;
    cursor: pointer;
    background-color: rgba(255,255,255,0.6);
}
#previous{
    left: 0px;
}
#next{
    right: 0px;
}

JS:

$(function(){
    var i=-1;
    function start () {
        i++;
        i=i%5;
        $("img").attr("src","img/"+(i+1)+".jpg");
        $("#dots>div").css("background","rgba(255,255,255,0.6)");
        $("#dots>div").eq(i).css("background","rgba(255,0,0,0.6)");
    }
    function change() {
        if(i<0)
            i=4;
        i=i%5;
        $("img").attr("src","img/"+(i+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,2000);
    $("#dots>div").mouseover(function () {
        clearInterval(time);
        i=$(this).index();
        change();
    });
    $("#dots>div").mouseout(function () {
        time=setInterval(start,2000);
    });
    $("img").mouseover(function() {
        clearInterval(time);
    });
    $("img").mouseout(function () {
        time=setInterval(start,2000);
    });
    $("#previous").click(function () {
        clearInterval(time);
        i--;
        change();
        time=setInterval(start,2000);
    });
    $("#next").click(function () {
        clearInterval(time);
        i++;
        change();
        time=setInterval(start,2000);
    });
});