CSS 变量 JS

通过将变量名称以字符串形式直接传递给动画参数,可以对包含数值或颜色值的 CSS 变量进行动画处理。
这种方法还可以对诸如 ::after::before 等伪元素上定义的属性进行动画处理,这些属性通常无法直接通过 JavaScript 访问。

为了使用由 WAAPI 驱动的 waapi.animate() 方法对 CSS 变量属性进行动画处理,您需要使用 CSS.registerProperty(propertyDefinition),否则将无法触发动画。

CSS 变量代码示例

import { animate, utils } from 'animejs';

// Assign the CSS variables to the properties of the animated elements
utils.set('.square', {
  '--radius': '4px',
  '--x': '0rem',
  '--pseudo-el-after-scale': '1', // applied to the pseudo element "::after"
  // Using a function prevents the variables from being converted
  borderRadius: () => 'var(--radius)',
  translateX: () => 'var(--x)',
});

// Animate the values of the CSS variables
animate('.square', {
  '--radius': '20px',
  '--x': '16.5rem',
  '--pseudo-el-after-scale': '1.55' // Animates the ":after" pseudo element of the element
});
<div class="medium row">
  <div class="css-variables square"></div>
</div>
<div class="medium row">
  <div class="css-variables square"></div>
</div>
<div class="medium row">
  <div class="css-variables square"></div>
</div>
.demo .css-variables.square:after {
  position: absolute;
  opacity: .5;
  top: 0;
  left: 0;
  content: "";
  display: block;
  width: 100%;
  height: 100%;
  background: currentColor;
  border-radius: inherit;
  transform: scale(var(--pseudo-el-after-scale));
}