如何在Javascript中更改关键帧的CSS属性?

我在from范围内有2个选择器to@keyframes,如下所示:

@keyframes pie {
    from {
        stroke-dashoffset: 0;
    }
    to {
        stroke-dashoffset: 77px;
    }
}

我想通过JavaScript更改to的属性,但是好像给style赋予.pie属性并没有达到我的期望。它直接将属性创建为.pie而不是to选择器。

这是我到目前为止所做的:

class Timer {
    constructor(elem) {
        this.elem = document.querySelector(elem);
        this.change();
    }
    change() {
        this.elem.style.strokeDashoffset = 10 + 'px';
    }
}
let getTimer = new Timer('.pie');
svg.timer {
    width: 40px;
    height: 40px;
    transform: rotateY(-180deg) rotateZ(-90deg);
}
circle {
    stroke-dasharray: 77px;
    stroke-dashoffset: 0px;
    stroke-width: 2px;
    stroke: brown;
    animation: pie 10s linear infinite forwards;
}
@keyframes pie {
    from {
        stroke-dashoffset: 0;
    }
    to {
        stroke-dashoffset: 77px;
    }
}
<div class="pie">
    <svg class="timer">
        <circle r="12" cx="20" cy="20">
        </circle>
    </svg>
</div>

是否有任何方法可以通过JavaScript在attribute选择器内更改to

limei2009 回答:如何在Javascript中更改关键帧的CSS属性?

最简单的方法是使用CSS-variables

class Timer {
    constructor(elem) {
        this.elem = document.querySelector(elem);
        this.change();
    }
    change() {
        this.elem.style.setProperty('--dashoffset',10 + 'px');
    }
}
let getTimer = new Timer('.pie');
svg.timer {
    width: 40px;
    height: 40px;
    transform: rotateY(-180deg) rotateZ(-90deg);
}
circle {
    stroke-dasharray: 77px;
    stroke-dashoffset: 0px;
    stroke-width: 2px;
    stroke: brown;
    animation: pie 10s linear infinite forwards;
}
@keyframes pie {
    from {
        stroke-dashoffset: 0;
    }
    to {
        stroke-dashoffset: 77px;
        stroke-dashoffset: var(--dashoffset);
    }
}
.pie { --dashoffset: 77px; }
<div class="pie">
    <svg class="timer">
        <circle r="12" cx="20" cy="20">
        </circle>
    </svg>
</div>

但是,它的支持仍然不是那么好,并且很难进行填充,因此,如果您必须处理旧版浏览器,则可能需要直接重写规则,方法是在整个@keyframes块后面附加一个新的

class Timer {
    constructor(elem) {
      this.elem = document.querySelector(elem);
      this.change();
    }
    change() {
      const style = document.createElement('style');
      style.textContent = `
@keyframes pie {
    from {
        stroke-dashoffset: 0;
    }
    to {
        stroke-dashoffset: ${ 10 }px;
  }
}`
      document.head.appendChild( style );
    }
}
let getTimer = new Timer('.pie');
svg.timer {
    width: 40px;
    height: 40px;
    transform: rotateY(-180deg) rotateZ(-90deg);
}
circle {
    stroke-dasharray: 77px;
    stroke-dashoffset: 0px;
    stroke-width: 2px;
    stroke: brown;
    animation: pie 10s linear infinite forwards;
}
@keyframes pie {
    from {
        stroke-dashoffset: 0;
    }
    to {
        stroke-dashoffset: 77px;
    }
}
<div class="pie">
    <svg class="timer">
        <circle r="12" cx="20" cy="20">
        </circle>
    </svg>
</div>

本文链接:https://www.f2er.com/3132957.html

大家都在问