最近有人问我这个问题:如何解决这个问题?创建一个允许设计人员配置动画的工具。为了促进这一点,在 JavaScript 中实现一个可以呈现这些动画的 AnimationSequence。
例如,如果设计者想要配置一个条形元素的填充,AnimationSequence 的用法看起来像这样
var barSequence = new AnimationSequence(bar, [
[100, { width: '10%' }],
[200, { width: '20%' }],
[200, { width: '50%' }],
[200, { width: '80%' }],
[300, { width: '90%' }],
[100, { width: '100%' }]
]);
barSequence.animate();
序列中每个步骤的第一个元素是该步骤发生之前的毫秒数,第二个元素是包含任意数量的 CSS 属性的对象。
您将如何实现 AnimationSequence?
最佳答案
您需要构建一个队列系统,然后根据第一个值调用每个动画帧。所以像这样...
var AnimationSequence = function(elem, opts) {
this.element = (typeof elem == "object") ? elem : $(elem); //jQuery
this.options = opts;
this.queue = [];
this.timer = 0;
this.init(opts);
}
AnimationSequence.prototype = {
init: function(opts) {
var that = this;
for(var i = 0, l = opts.length; i < l; i++) {
this.queue.push({delay: opts[i][0], command: opts[i][1]});
}
this.deQueue();
},
deQueue: function() {
if(this.queue.length) {
var animation = this.queue.shift(),
that = this;
this.timer = setTimeout(function() {
that.element.animate(animation.command, function() {
that.deQueue();
});
}, animation.delay);
}
}
};
$(function() {
var barSequence = new AnimationSequence(".bar", [
[100, { width: '10%' }],
[200, { width: '20%' }],
[200, { width: '50%' }],
[200, { width: '80%' }],
[300, { width: '90%' }],
[100, { width: '100%' }]
]);
});
显然你会有 html...
<div id="bar-holder">
<div class="bar"></div>
</div>
还有CSS...
#bar-holder {
width: 100%;
padding: 5px;
background: #ccc;
}
.bar {
height: 25px;
background: red;
}
工作 jsfiddle 示例... https://jsfiddle.net/kprxcos4/ 显然,您可能想要加强它一点,但这是可以处理参数和自定义字段的动画队列系统的开始。
关于javascript - 如何从以下原型(prototype)创建动画工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42377000/