添加构造函数

构造函数在作为 Scope 的 add()addOnce() 方法的回调函数传入后,会立即在 Scope 的上下文中被调用。
Scope 会注册并跟踪所有在构造函数内部声明的动画 (animations)、定时器 (timers)、时间轴 (timelines)、可动画对象 (animatables)、可拖拽对象 (draggables)、滚动监听 (onScrolls),甚至是其他作用域 (scopes)。

// Execute a constructor every time a media query changes
scope.add(constructor);

// Execute a constructor once
scope.addOnce(constructorFunction);

构造函数参数

名称 类型
self 当前的 Scope 实例

返回值 (可选)

一个清理 Function,在 Scope 被还原或媒体查询发生变化时调用。

添加构造函数代码示例

import { utils, animate, createScope, createDraggable } from 'animejs';

createScope({
  mediaQueries: { isSmall: '(max-width: 200px)' },
  defaults: { ease: 'linear' },
})
.add(self => {

  /* Media queries state are accessible on the matches property */
  const { isSmall } = self.matches;
  /* The $() utility method is also scoped */
  const [ $square ] = utils.$('.square');

  if (self.matches.isSmall) {
    /* Only animate the square when the iframe is small */
    animate($square, {
      rotate: 360,
      loop: true,
    });
  } else {
    /* Only create the draggable when the iframe is large enough */
    $square.classList.add('draggable');
    createDraggable($square, {
      container: document.body,
    });
  }
  
  return () => {
    /* Removes the class 'draggable' when the scope reverts itself */
    $square.classList.remove('draggable');
  }

});
<div class="iframe-content resizable">
  <div class="large centered row">
    <div class="col">
      <div class="square"></div>
    </div>
  </div>
</div>