轮播图怎么写

113 阅读1分钟
<style>
    .box {
        width: 500px;
        height: 300px;
        margin: 30px auto;
        border: 1px solid cyan;
        position: relative;
    }

    .img-list img {
        width: 500px;
        height: 300px;
        display: block;
        position: absolute;
        left: 0;
        top: 0;
    }

    .left,
    .right {
        position: absolute;
        width: 30px;
        line-height: 40px;
        text-align: center;
        color: #fff;
        background-color: rgba(0,0,0,.15);
        font-size: 20px;
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
    }

    .left {
        left: 0;
        border-top-right-radius: 18px;
        border-bottom-right-radius: 18px;
    }

    .right {
        right: 0;
        border-top-left-radius: 18px;
        border-bottom-left-radius: 18px;
    }
</style>



<div class="box">
    <div class="img-list">
        <img src="./imgs/1.jpg" alt="">
        <img src="./imgs/2.jpg" alt="">
        <img src="./imgs/3.jpg" alt="">
        <img src="./imgs/4.jpg" alt="">
    </div>
    <div class="left">&lt;</div>
    <div class="right">&gt;</div>
</div>




<script src="./jquery-1.12.4.js"></script>
<script>
    let i = 0;
    let timer = null
    $('img').eq(i).show().siblings().hide();
    /* 自动播放 */
    show();

    $('.left').click(function () {
        /* 先清空定时器 阻止自动播放 */
        clearInterval(timer)
        i--;
        /* 防止减到-1 找不到对应的图片 */
        if (i == -1) {
            i = $('img').length - 1
        }
        /* 展示当前对应的图片其他图片淡出 */
        $('img').eq(i).show().siblings().hide();
        /* 继续开始自动播放 */
        show();
    })

    $('.right').click(function () {
        /* 先清空定时器 阻止自动播放 */
        clearInterval(timer)
        i++;
        /* 防止减到-1 找不到对应的图片 */
        if (i == $('img').length) {
            i = 0
        }
        /* 展示当前对应的图片其他图片淡出 */
        $('img').eq(i).show().siblings().hide();
        /* 继续开始自动播放 */
        show();
    })

    /* 定时器 过2秒 显示一张图 显示最后一张图的时候 
    再跳到第一张 */

    function show() {
        timer = setInterval(function () {
            i++
            if (i == $('img').length) {
                i = 0
            }
            /* fadeIn淡入  fadeOut淡出 */
            $('img').eq(i).fadeIn().siblings().fadeOut();
        }, 2000)
    }

</script>