添加构造函数

构造函数在作为 Scope 的 add()addOnce() 方法的回调传递后,会立即在 Scope 的上下文中被调用。
Scope 会注册并跟踪构造函数中声明的所有动画、计时器、时间线、可动画对象、可拖拽对象、滚动事件处理函数,甚至其他 Scope。

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

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

构造函数参数

名称 类型
self 当前的 Scope 实例

返回 (可选)

当作用域被恢复或媒体查询发生变化时调用的清理 Function

添加构造函数代码示例

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>