原生js写透明度轮播

css代码


html代码

js代码

(function () {
        var prevIndex,nextIndex
        var len
        var times
        init()
        function init() {
            prevIndex = nextIndex = 0
            len = document.querySelectorAll('#lbt1 img').length
            var lefts = document.querySelector('.lefts')
            var rights = document.querySelector('.rights')
            var list = document.querySelectorAll('.ull li')
            var lbt = document.querySelector('#lbt')

            lefts.onclick = function(){
                toPrev()
            }
            rights.onclick = function(){
                toNext()
            }

            for(var i= 0; i{
                toNext()
            },2000)
           
        }
        function stop(){
            clearInterval(times)
        }


    })()

这是封装的运动函数motion

function getStyle(ele, property) {
    if (getComputedStyle) {
        return getComputedStyle(ele, null)[property]
    } else {
        return ele.currentStyle[property]
    }
}
function motion(ele, propertyS,fn) {
    clearInterval(ele.timer)
    ele.timer = setInterval(() => {
        var flag = 1
        for (property in propertyS) {
            var values
            var target = propertyS[property]

            if (property === 'opacity') {
                values = Math.round(parseFloat(getStyle(ele, property)) * 100)
            } else {
                values = parseInt(getStyle(ele, property))
            }

            var speed = (target - values) / 30
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)

            values += speed
            if(property === 'zIndex'){
                values = target
            }
            if(values!=target){
                flag = 0
            }
            if (property === 'opacity') {
                ele.style.opacity = values / 100
            } else if(property === 'zIndex'){
                ele.style.zIndex = values
            } else {
                ele.style[property] = values + 'px'
            }
        }

        if(flag){
            fn&&fn()
            clearInterval(ele.timer)
        }
    }, 10)
}

其实轮播图的原理很简单,就是图片的透明度切换,难点在于边界条件的判断,这个搞清楚了就可以写出来了

你可能感兴趣的:(原生js写透明度轮播)