0

我有以下 CSS 关键帧:

  @keyframes progressStatus 
  {
    to 
    {
      stroke-dashoffset: 165;
    }
  }

我正在尝试使用 Javascript 将值 165 更改为其他值。

4

2 回答 2

2

对于这个特定示例,您可以使用 CSS 变量。

每次单击 div 时,这个简单的代码片段都会更改一个名为 --strokeDashoffset 的变量(并在有动画和没有动画之间切换,仅用于演示)。

div {
  --strokeDashoffset: 165px; /* initial position */
  background-color: magenta;
  width: var(--strokeDashoffset);
  height: 5vmin;
  animation: none;
  animation-fill-mode: forwards;
  animation-duration: 1s;
  animation-iteration-count: 1;
}
.strokeDashoffset {
  animation-name: progressStatus;
}
  @keyframes progressStatus 
  {
    to 
    {
      stroke-dashoffset: var(--strokeDashoffset);
    }
  }
<div onclick="this.classList.toggle('strokeDashoffset'); this.style.setProperty('--strokeDashoffset', Math.random(0,1)*100 + 'vmin');" >CLICK ME</div>

于 2021-05-28T18:56:01.377 回答
1

虽然另一个答案中的 CSS 变量方法更好,但这是一种直接修改相关 CSS 的方法,因为我已经输入了它。如果您不能依赖 CSS 自定义属性(变量)或 polyfill,这可能会很有用。

在 CSS 对象模型中,@keyframes规则有自己的一组子规则,对应于关键帧本身(fromto/或百分比)。因此,如果您的示例是文档中的第一个样式表(并且没有其他规则):

const stylesheet = document.stylesheets[0];
const progressStatus = stylesheet.cssRules[0];
const toKeyframe = progressStatus.cssRules[0];
toKeyframe.style.strokeDashoffset = '170 80'; // or whatever desired value

通过数组索引选择样式表和嵌套规则很麻烦,容易出错并且很容易因更改而中断。在生产代码中,您至少希望通过使用各种测试迭代所有规则来定位规则,例如rule.type === CSSRule.KEYFRAMES_RULE && rule.name === 'progressStatus'.

于 2021-05-28T18:58:14.017 回答