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



我在@keyframes范围内有两个选择器fromto,如下所示:

@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更改to选择器内部的attribute吗?

最简单的是使用CSS变量:

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>

然而,它的支持仍然没有那么好,而且很难进行polyfill,所以如果你必须处理遗留浏览器,你可能需要直接重写规则,方法是添加一个新的<style>与整个@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>

最新更新