轮播图案例

290 阅读1分钟

css部分 ` * { margin: 0; padding: 0; }

    div {
        position: relative;
        width: 730px;
        height: 454px;
        overflow: hidden;
    }

    section {
        position: absolute;
        display: flex;
        top: 0px;
        left: 0px;
        /* width: 730px; */
        height: 454px;
        transition: all 500ms;
    }

    ul {
        display: flex;
        position: absolute;
        right: 20px;
        bottom: 20px;
        font-weight: bold;
        color: white;
    }

    li {
        list-style: none;
        background-color: pink;
        padding: 7px 13px;
        margin: 5px;
        cursor: pointer;
    }`
   
    html部分
        <div>
    <section id="sec">
        <img src="./images/1.jpg">
        <img src="./images/2.jpg">
        <img src="./images/3.jpg">
        <img src="./images/4.jpg">
    </section>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>
</div>
js部分
var osec2 = document.getElementById('sec2')
    var osec = document.getElementById('sec')
    var oul = document.querySelector('ul')
    var oli = oul.children
    //自动轮播
    function Lunbt(osec, i, oli) {
        this.osec = osec
        this.i = i
        this.oli = oli
    }
    oli[0].style.backgroundColor="black"
    Lunbt.prototype.show = function () {
        if (this.i == 4) {
            this.i = 0
        }
        this.osec.style.left = -this.i * 730 + 'px'
        for (var j = 0; j < oli.length; j++) {
            this.oli[j].style.backgroundColor = "pink"
        }
        this.oli[this.i].style.backgroundColor = 'black'
        this.i++
    }
    var Lunbt1 = new Lunbt(osec, 0, oli)
    var go = setInterval(function () {//定时器
        Lunbt1.show()
    }, 1000)


    //手动轮播
    function Handlunb(oli1, osec1) {
        this.oli1 = oli1
        this.osec1 = osec1
    }
    Handlunb.prototype.show = function () {
        for (var k = 0; k < this.oli1.length; k++) {
            var ev = ev || event
            var a = ev.target.index
            if (k == a) {
                this.oli1[k].style.backgroundColor = "black"
                this.osec1.style.left = -k * 730 + 'px'
            } else {
                this.oli1[k].style.backgroundColor = "pink"
            }
        }

    }
    var Handlunb1 = new Handlunb(oli, osec)

    //鼠标放上去 或滑出
    for (var l = 0; l < oli.length; l++) {
        oli[l].index = l
        oli[l].onmouseenter = function () {
            Handlunb1.show()
            clearInterval(go)
        }
        oli[l].onmouseout = function () {
            clearInterval(go)
         go= setInterval(function () {
                Lunbt1.show()
            }, 1000)
        }
    }