超简单原生JS轮播图

173 阅读1分钟

HTML 部分

<div class="wrapper" id="wrapper">
    <ul id="pic">
        <li><img src="./image/1.jpg" alt=""></li>
        <li><img src="./image/2.jpg" alt=""></li>
        <li><img src="./image/3.jpg" alt=""></li>
        <li><img src="./image/4.jpg" alt=""></li>
        <li><img src="./image/5.jpg" alt=""></li>
    </ul>

    <ol id="list">
        <li class="selected"></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ol>
</div>

CSS 部分

* {margin: 0;padding: 0;box-sizing: border-box;}

body {background: #f7f7f7;}

img {width: 100%;height: 100%;}

ul, li {list-style: none;}

---------------------------------------------------------

.wrapper{
    position: relative;
    width: 300px;
    height: 300px;
    margin: 100px auto;


    overflow: hidden;
}

.wrapper > ul {
    position: absolute;
}

.wrapper > ul > li {
    height: 300px;
}

.wrapper > ol {
    position: absolute;
    left: 50%;
    bottom:0;
    transform: translate(-50%);
    display: flex;
    flex-direction: row;
    text-align: center;
}

.wrapper > ol > li {
    height: 20px;
    width: 20px;
    line-height: 20px;
    background: transparent;
    border-radius: 50%;
    cursor: pointer;
    border:1px solid #ccc;
}

.wrapper ol .selected{
    background: #ccc;
    color: #fff;
}

JS 部分

const wrapper = document.getElementById('wrapper')
const pic = document.getElementById('pic')
const list = document.getElementById('list').getElementsByTagName('li')
console.log(list)

window.onload = function () {
    let index = 0
    let timer = null

    function autoPlay() {
        index++
        if (index >= list.length) {
            index = 0
        }
        changeImg(index)
    }

    function changeImg(curIndex) {
        for (let i = 0; i < list.length; i++) {
            list[i].className = ""
        }
        list[curIndex].className = "selected"
        pic.style.marginTop = -300 * curIndex + "px"
        index = curIndex
    }

    timer = setInterval(autoPlay, 2000)


    for (let j = 0; j < list.length; j++) {
        list[j].id = j
        list[j].onclick = function () {
            clearInterval(timer)
            changeImg(this.id)
        }
    }
}

效果预览:请点这里

源码链接:请点这里