JS缓冲运动与透明渐变

2017-01-04  本文已影响41人  duJing

HTML部分:

<!DOCTYPE html>
<html>
<meta charset="utf-8"/>
<head>
<link rel="stylesheet" type="text/css" href="dome.css"/>
</head>
<body>
<input type="button" value="按钮" id="btn"/>
<div id="box">box</div>
<div id="container"></div>
<script src="../base.js"></script>
<script src="../tool.js"></script>
<script src="dome.js"></script> 
</body>
</html>

CSS部分:

body {
    margin:0px;
    padding:0px;
}
#box {
    position : absolute;
    width : 100px;
    height : 100px;
    background : red;
    left : 100px;
    top : 100px;
}
#container {
    width : 300px;
    height : 500px;
    background: #ccc;
}

JS部分:

// 跨浏览器获取css样式
function getStyle(element, attr) {
    var value = 0;
    if (typeof window.getComputedStyle != 'undefined') {    // W3C
        value = window.getComputedStyle(element, null)[attr];
    } else if (typeof element.currentStyle != 'undefined') {    // IE
        value = element.currentStyle[attr];
    }
    return value;
}
// 加载DOM
(function () {
    var div = document.getElementById("box");
    $("#btn").click(function () {
        var timer = setInterval(function () {
            element.style[attr] = parseInt(getStyle(element, attr)) + step + "px";
            if (parseInt(getStyle(div, "left")) >= 300) clearInterval(timer);
            document.getElementById("container").innerHTML += getStyle(element, attr) + "<br/>";
        }, 30);
    });
})();

这样我们,就可以简单的通过单击按钮使得DIV运动起来,实现简单的动画
接下来,我们将这个简单的动画封装一下下

Base.prototype.animate = function (attr, target, step, t) {
    for (var i = 0, len = this.elements.length; i < len; i++) {
        var element = this.elements[i];
        var timer = setInterval(function () {
            element.style[attr] = parseInt(getStyle(element, attr)) + step + "px";
            if (parseInt(getStyle(element, attr)) >= target)    clearInterval(timer);
            document.getElementById("container").innerHTML += getStyle(element, attr) + "<br/>";
        }, t);
    }
    return this;
}

前台调用部分:

(function () {
    var div = document.getElementById("box");
    $("#btn").click(function () {
        $("#box").animate("left", 300, 10, 30);
    });
})();

由于animate()方法的参数计较多,容易混淆,我们该为传个对象,
并且加入增量alter

Base.prototype.animate = function (obj) {
    for (var i = 0, len = this.elements.length; i < len; i++) {
        var element = this.elements[i];
        var attr = obj.attr !== undefined ? obj.attr : "left";
        var start = obj.attr !== undefined ? obj.attr : parseInt(getStyle(element, attr));
        // 当alter和target同时存在时,忽略alter
        var alter = obj.alter;
        var target = obj.target;
        if (alter !== undefined && target === undefined) {
            target = start + alter;
        } else if (alter === undefined && target === undefined) {
            throw new Error("增量alter或者目标量target两个值必须填一个");
        }
        var step = obj.step !== undefined ? obj.step : 10;
        var t = obj.t !== undefined ? obj.t : 30;

        var timer = setInterval(function () {
            element.style[attr] = parseInt(getStyle(element, attr)) + step + "px";
            if (parseInt(getStyle(element, attr)) >= target)    clearInterval(timer);
            document.getElementById("container").innerHTML += getStyle(element, attr) + "<br/>";
        }, t);
    }
    return this;
}

前台调用:

(function () {
    var div = document.getElementById("box");
    $("#btn").click(function () {
        $("#box").animate({
            attr : "left",
            start : 100,
            alter : 900,    // 当alter和target同时存在时,忽略alter
            target : 300,
            step : 10,
            t : 30
        });
    });
})();

问题:当我们将step设置为7的时候,div到达303才能停止,这显然不是我们想要的结果
因此我们在div.style.left >= target时,让其直接等于target

window.timer = setInterval(function () {
    if (parseInt(getStyle(element, attr)) >= target) {
        element.style[attr] = target + 'px';
        clearInterval(timer);
    } else {
        element.style[attr] = parseInt(getStyle(element, attr)) + step + "px";
    }
    document.getElementById("container").innerHTML += getStyle(element, attr) + "<br/>";
}, t);

问题:当div运动到303时,它会自动调回300,这时会有一点卡的感觉
因此我们想要div在296的时候,直接到300,这样更符合。
当div的left属性与target的绝对值小于等于step步长时,我们直接让其等于target

var t = obj.t !== undefined ? obj.t : 30;
window.timer = setInterval(function () {
    if (Math.abs(parseInt(getStyle(element, attr)) - target) <= step) {
        element.style[attr] = target + 'px';
        clearInterval(timer);
    } else {
        element.style[attr] = parseInt(getStyle(element, attr)) + step + "px";
    }
    document.getElementById("container").innerHTML += getStyle(element, attr) + "<br/>";
}, t);

问题:当我们不停的单击按钮时,就会不停的触发事件,导致不停的调用定时器,使得div运动的速度越来越快
因此,我们需要将timer放在全局变量中,且在定时器每次被调用时先清除一下

var timer = null;       // 将定时器变量放在全局中
Base.prototype.animate = function (obj) {
    for (var i = 0, len = this.elements.length; i < len; i++) {
        var element = this.elements[i];
        var attr = obj.attr !== undefined ? obj.attr : "left";
        var start = obj.attr !== undefined ? obj.attr : parseInt(getStyle(element, attr));
        // 当alter和target同时存在时,忽略alter
        var alter = obj.alter;
        var target = obj.target;
        if (alter !== undefined && target === undefined) {
            target = start + alter;
        } else if (alter === undefined && target === undefined) {
            throw new Error("增量alter或者目标量target两个值必须填一个");
        }
        var step = obj.step !== undefined ? obj.step : 10;
        var t = obj.t !== undefined ? obj.t : 30;
        clearInterval(timer);       // 每次才定时器干活前,先把以前的定时器清除掉,防止重复调用
        timer = setInterval(function () {
            if (Math.abs(parseInt(getStyle(element, attr)) - target) <= step) {
                element.style[attr] = target + 'px';
                clearInterval(timer);
            } else {
                element.style[attr] = parseInt(getStyle(element, attr)) + step + "px";
            }
            document.getElementById("container").innerHTML += getStyle(element, attr) + "<br/>";
        }, t);
    }
    return this;
}

问题:当我们想要让div向左移动时,我们需要将step设置为-7,
且当div的left属性与target的差值小于等于step步的绝对值时,我们让其直接等于target

timer = setInterval(function () {
    if (step > 0 && Math.abs(parseInt(getStyle(element, attr)) - target) <= step) {
        element.style[attr] = target + 'px';
        clearInterval(timer);
    // 向左向下移动
    } else if (step < 0 && parseInt(getStyle(element, attr)) - target <= Math.abs(step)) {
        element.style[attr] = target + 'px';
        clearInterval(timer);
    }else {
        element.style[attr] = parseInt(getStyle(element, attr)) + step + "px";
    }
    document.getElementById("container").innerHTML += getStyle(element, attr) + "<br/>";
}, t);

前台调用

(function () {
    var div = document.getElementById("box");
    $("#btn").click(function () {
        $("#box").animate({
            attr : "top",
            start : 100,
            target : 0,
            step : -7,
            t : 30
        });
    });
})();

问题:我们设置step为负时,会感觉很别扭,我们需要让其为正
因此当div的left属性大于target时,我们让step取负

if (parseInt(getStyle(element, attr)) >= target) step = - step;

前台调用

$("#box").animate({
    attr : "left",
    start : 100,
    target : 0,
    step : 7,       // 还是为正
    t : 30
});

问题:当div的目标值到达了300,我们再次单击按钮时,它就不动了
因此,我们需要设置:当div到达300了,我们让它重置为start,这样它可以重新运动
element.style[attr] = start + ‘px’;
问题:当我们前台调用attr属性为left时,这样不太清晰,我们用x表示left,
y表示top,w表示width,x表示height

var attr = obj.attr === 'x' ? 'left' : obj.attr === 'y' ? 'top' :
    obj.attr === 'w' ? 'width' : obj.attr === 'h' ? 'height' : "left";

前台调用

$("#box").animate({
    attr : "w",
    start : 100,
    target : 300,
    step : 7,
    t : 30
});

问题:我们需要缓冲运动,这样就使得运动更加的逼真
分析:缓冲运动的意思就是随着div的left属性值与target目标点的差值变小,运动的速度(speed)也逐渐变小

var timer = null;
Base.prototype.animate = function (obj) {
    for (var i = 0, len = this.elements.length; i < len; i++) {
        var element = this.elements[i];
        var attr = obj.attr === 'x' ? 'left' : obj.attr === 'y' ? 'top' :
                   obj.attr === 'w' ? 'width' : obj.attr === 'h' ? 'height' : "left";
        var start = obj.start !== undefined ? obj.start : parseInt(getStyle(element, attr));
        // 当alter和target同时存在时,忽略alter
        var alter = obj.alter;
        var target = obj.target;
        if (alter !== undefined && target === undefined) {
            target = start + alter;
        } else if (alter === undefined && target === undefined) {
            throw new Error("增量alter或者目标量target两个值必须填一个");
        }
        var step = obj.step !== undefined ? obj.step : 10;
        if (start >= target) step = - step;
        var speed = obj.speed !== undefined ? obj.speed : 6;
        var type = obj.type === 0 ? "contant" : obj.type === 1 ? "buffer" : "buffer";
        element.style[attr] = start + 'px';
        var t = obj.t !== undefined ? obj.t : 30;

        clearInterval(timer);
        timer = setInterval(function () {
            // 缓冲运动
            if (type === "buffer") {
                var temp = (target - parseInt(getStyle(element, attr))) / speed;
                step = step > 0 ? Math.ceil(temp) : Math.floor(temp);
            }
            // 因为step的范围不可能为0
            if (step > 0 && Math.abs(parseInt(getStyle(element, attr)) - target) <= step) {
                getTarget();
            } else if (step < 0 && parseInt(getStyle(element, attr)) - target <= Math.abs(step)) {
                getTarget();
            }else {
                element.style[attr] = parseInt(getStyle(element, attr)) + step + "px";
            }
            document.getElementById("container").innerHTML += step + "<br/>";
        }, t);
        function getTarget () {
            element.style[attr] = target + 'px';
            clearInterval(timer);
        }
    }
    return this;
}

前台调用

(function () {
    var div = document.getElementById("box");
    $("#btn").click(function () {
        $("#box").animate({
            attr : "x",
            start : 100,
            target : 300,
            step : 7,
            speed : 5,
            t : 30,
            type : 1
        });
    });
})();

我们讨论了缓冲运动之后,接下来,我们来讨论一下渐变透明。
当然,这建立在缓冲运动的基础上,我们只需找出动画与渐变透明的不同点即可
首先改变的是css部分:

body {
    margin:0px;
    padding:0px;
}
#box {
    position : absolute;
    width : 100px;
    height : 100px;
    background : red;
    left : 100px;
    top : 100px;
    /*新加的透明度*/
    opacity : 0.3;
    filter : alpha(opacity = 30);
}
#container {
    width : 300px;
    height : 500px;
    background: #ccc;
}

接着,我们进入主题吧
第一步,我们修改attr,用o,代替opacity属性

var attr = obj.attr === 'x' ? 'left' : obj.attr === 'y' ? 'top' :
   obj.attr === 'w' ? 'width' : obj.attr === 'h' ? 'height' : 
   obj.attr === 'o' ? 'opacity' : left;

第二步,设置初始值

if (attr === 'opacity') {
    element.style.opacity = start / 100;
    element.style.filter = "alpha(opacity=" + start + ")";
} else {
    element.style[attr] = start + 'px';
}

第三步,修改运动

if (attr === 'opacity') {
    if (step > 0 && Math.abs(parseFloat(getStyle(element, attr)) * 100 - target) <= step) {
        getOpacity();
    } else if (step < 0 && parseFloat(getStyle(element, attr)) * 100 - target <= Math.abs(step)) {
        getOpacity();
    }else {
        var temp = parseFloat(getStyle(element, attr)) * 100;
        element.style.opacity = (temp + step) / 100;
        element.style.filter = "alpha(opacity=" + parseInt(getStyle(element, attr)) + ")";
    }
} else {
    // 因为step的范围不可能为0
    if (step > 0 && Math.abs(parseInt(getStyle(element, attr)) - target) <= step) {
        getTarget();
    } else if (step < 0 && parseInt(getStyle(element, attr)) - target <= Math.abs(step)) {
        getTarget();
    }else {
        element.style[attr] = parseInt(getStyle(element, attr)) + step + "px";
    }
}
function getTarget () {
    element.style[attr] = target + 'px';
    clearInterval(timer);
}
function getOpacity () {
    var temp = parseFloat(getStyle(element, attr)) * 100;
    element.style.opacity = target / 100;
    element.style.filter = "alpha(opacity=" + target + ")";
    clearInterval(timer);
}

第四步,设置缓冲

if (type === "buffer") {
    var temp = attr === 'opacity' ? (target - parseFloat(getStyle(element, attr)) * 100) / speed : 
    (target - parseInt(getStyle(element, attr))) / speed;
    step = step > 0 ? Math.ceil(temp) : Math.floor(temp);
}

下面是完整的JS代码:

var timer = null;
Base.prototype.animate = function (obj) {
    for (var i = 0, len = this.elements.length; i < len; i++) {
        var element = this.elements[i];
        var attr = obj.attr === 'x' ? 'left' : obj.attr === 'y' ? 'top' :
                   obj.attr === 'w' ? 'width' : obj.attr === 'h' ? 'height' : 
                   obj.attr === 'o' ? 'opacity' : left;
        var start = obj.start !== undefined ? obj.start :
                    attr === 'opacity' ?  parseFloat(getStyle(element, attr)) * 100 :
                        parseInt(getStyle(element, attr));
        // 当alter和target同时存在时,忽略alter
        var alter = obj.alter;
        var target = obj.target;
        if (alter !== undefined && target === undefined) {
            target = start + alter;
        } else if (alter === undefined && target === undefined) {
            throw new Error("增量alter或者目标量target两个值必须填一个");
        }
        var step = obj.step !== undefined ? obj.step : 10;
        if (start >= target) step = - step;
        var speed = obj.speed !== undefined ? obj.speed : 6;
        var type = obj.type === 0 ? "contant" : obj.type === 1 ? "buffer" : "buffer";
        if (attr === 'opacity') {
            element.style.opacity = start / 100;
            element.style.filter = "alpha(opacity=" + start + ")";
        } else {
            element.style[attr] = start + 'px';
        }
        var t = obj.t !== undefined ? obj.t : 30;

        clearInterval(timer);
        timer = setInterval(function () {
            // 缓冲运动
            if (type === "buffer") {
                var temp = attr === 'opacity' ? (target - parseFloat(getStyle(element, attr)) * 100) / speed : 
                (target - parseInt(getStyle(element, attr))) / speed;
                step = step > 0 ? Math.ceil(temp) : Math.floor(temp);
            }
            if (attr === 'opacity') {
                if (step > 0 && Math.abs(parseFloat(getStyle(element, attr)) * 100 - target) <= step) {
                    getOpacity();
                } else if (step < 0 && parseFloat(getStyle(element, attr)) * 100 - target <= Math.abs(step)) {
                    getOpacity();
                }else {
                    var temp = parseFloat(getStyle(element, attr)) * 100;
                    element.style.opacity = (temp + step) / 100;
                    element.style.filter = "alpha(opacity=" + parseInt(getStyle(element, attr)) + ")";
                }
            } else {
                // 因为step的范围不可能为0
                if (step > 0 && Math.abs(parseInt(getStyle(element, attr)) - target) <= step) {
                    getTarget();
                } else if (step < 0 && parseInt(getStyle(element, attr)) - target <= Math.abs(step)) {
                    getTarget();
                }else {
                    element.style[attr] = parseInt(getStyle(element, attr)) + step + "px";
                }
            }
            document.getElementById("container").innerHTML += parseFloat(getStyle(element, attr)) * 100 + "<br/>";
        }, t);
        function getTarget () {
            element.style[attr] = target + 'px';
            clearInterval(timer);
        }
        function getOpacity () {
            var temp = parseFloat(getStyle(element, attr)) * 100;
            element.style.opacity = target / 100;
            element.style.filter = "alpha(opacity=" + target + ")";
            clearInterval(timer);
        }
    }
    return this;
}

前台调用

(function () {
    var div = document.getElementById("box");
    $("#btn").click(function () {
        $("#box").animate({
            attr : "o",
            start : 30,
            target : 100,
            step : 6,
            speed : 7,
            type : 1
        });
    });
})();
上一篇下一篇

猜你喜欢

热点阅读