Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

匀速运动动画 #10

Closed
wuxianqiang opened this issue Dec 27, 2017 · 0 comments
Closed

匀速运动动画 #10

wuxianqiang opened this issue Dec 27, 2017 · 0 comments

Comments

@wuxianqiang
Copy link
Owner

function linear(t, b, c, d) {
        return c / d * t + b
    }

    function tween(element, target, duration, callback) {
        let change = {};
        let begin = {};
        for (let key in target) {
            begin[key] = getCss(element, key);
            change[key] = removeUnit(target[key]) - begin[key];
        }

        let time = 0;
        let timing = setInterval(() => {
            time += 20;
            if (time >= duration) {
                clearInterval(timing);
                for (let key in target) {
                    setCss(element, key, target[key]);
                }
                callback && callback.call(element);
                return;
            }
            for (let key in target) {
                let current = linear(time, begin[key], change[key], duration);
                setCss(element, key, current);
            }
        }, 20)
    }

    function getCss(ele, attr) {
        let value = window.getComputedStyle(ele)[attr];
        return removeUnit(value);
    }

    function removeUnit(value) {
        let reg = /^[-+]?([1-9]\d+|\d)(\.\d+)?(px|pt|em|rem)$/;
        if (isNaN(value) && reg.test(value)) return parseFloat(value);
        if (isNaN(value)) return Number(value);
        return value
    }

    function setCss(ele, attr, val) {
        let reg = /^(width|height|top|bottom|left|right|(margin|padding)(Top|Left|Bottom|Right)?)$/;
        if (!isNaN(val) && reg.test(attr)) {
            ele.style[attr] = val + "px";
            return;
        }
        ele.style[attr] = val;
    }


    let box = document.getElementById("box");
    tween(box, {left: 500, top: 500}, 2000,function () {
        this.style.background = "pink";
    })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant