添加构造函数
构造函数在作为 Scope 的回调传入后,会立即在 Scope 的上下文中被调用,这些回调是 Scope 的 add()
或 addOnce()
方法。
Scope 会注册并跟踪所有在构造函数内部声明的动画、计时器、时间轴、可动画对象、可拖动对象、滚动事件以及其他 Scope。
// 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>