js 封装多属性运动函数


## **封装一个获取属性的函数**

function getStyle(ele, property) {
    if (getComputedStyle) {
        return getComputedStyle(ele, null)[property]
    } else {
        return ele.currentStyle[property]
    }
}

## **封装的运动函数**

function motion(ele, propertyS, fn) {
    clearInterval(ele.timerId)
    ele.timerId = setInterval(() => {
        var flag = 1
        for (property in propertyS) {
            var value
            var target = propertyS[property]
            if (property === 'opacity') {
                value = Math.round(parseFloat(getStyle(ele, property)) * 100)
            } else {
                value = parseInt(getStyle(ele, property))
            }
            var speed = (target - value) / 30
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
            value += speed
            if(property==='zIndex'){
                value = target
            }
            if (value != target) {
                flag = 0
            }
            if (property === 'opacity') {
                ele.style.opacity = value / 100
            } else if(property === 'zIndex'){
                ele.style.zIndex = value
            } else{
                ele.style[property] = value + 'px'
            }

        }
        if (flag) {
            fn && fn()
            clearInterval(ele.timerId)
        }

    }, 10)
}

你可能感兴趣的:(javascript)