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));
}