javascript - 如何从以下原型(prototype)创建动画工具

标签 javascript jquery css animation jquery-animate

最近有人问我这个问题:如何解决这个问题?创建一个允许设计人员配置动画的工具。为了促进这一点,在 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/

相关文章:

javascript - 可点击网站的服装按钮..就像这个

javascript - 在 JavaScript 中创建 `data-win-control`

javascript - 如何检查android权限 promise 是否成功?

jquery:获取和设置图像,从背景CSS重复

jquery - 有人可以帮我从 Jquery Plugin Masonry 切换到 Isotope 吗?

javascript - 通过浏览文件夹为每个 div 分配不同的图像

javascript - Background Size : Contain, 缩放后得到Size

javascript - Jquery: <a> 链接点击 preventDefault() 不工作?

javascript - iOS UIWebView - 自动点击 FORM 按钮..如何实现?

html - 响应式背景图片在移动设备尺寸下无法填满整个页面长度