SVG动画在以编程方式设置样式时有效,但在仅使用样式表时则不起作用

时间:2014-12-16 01:00:59

标签: javascript css svg

我有一个包含样式表的svg文档。使用样式表我可以设置rect的填充(样式表正在工作)。我要做的是设置一个变色动画。我有以下样式表:

@keyframes blinking-effect {
    0% {
        stroke: rgba(255, 255, 0, 1);
        fill: rgba(0, 220, 0, 1);
    }
    100% {
        stroke: rgba(255, 255, 255, 0);
        fill: rgba(0, 0, 220, 1);
    }
}
.animation {
    animation-name: "blinking-effect";
    animation-duration: "0.5s";
    animation-iteration-count: "infinite";
    animation-timing-function: "ease-in-out";
    animation-direction: "alternate";
}


<rect id="rect1" x="0" y="0" width="50%" y="50%" class="animation " />

我不知道为什么这不起作用。但是,当我执行以下代码时它确实有效:

document.getElementById("rect1").style.setProperty("animation-name", "blinking-effect");
document.getElementById("rect1").style.setProperty("animation-duration", "0.5s");
document.getElementById("rect1").style.setProperty("animation-iteration-count", "infinite");
document.getElementById("rect1").style.setProperty("animation-timing-function", "ease-in-out");
document.getElementById("rect1").style.setProperty("animation-direction", "alternate");

有没有办法在不使用JavaScript的情况下执行此操作?

2 个答案:

答案 0 :(得分:1)

这样做。

.animate {
  -webkit-animation: blinkingEffect 0.5s infinite ease-in-out alternate;
  animation: blinkingEffect 0.5s infinite ease-in-out alternate;
}
@-webkit-keyframes blinkingEffect {
  0% {
    stroke: rgba(255, 255, 0, 1);
    fill: rgba(0, 220, 0, 1);
  }
  100% {
    stroke: rgba(255, 255, 255, 0);
    fill: rgba(0, 0, 220, 1);
  }
}
@-moz-keyframes blinkingEffect {
  0% {
    stroke: rgba(255, 255, 0, 1);
    fill: rgba(0, 220, 0, 1);
  }
  100% {
    stroke: rgba(255, 255, 255, 0);
    fill: rgba(0, 0, 220, 1);
  }
}
@keyframes blinkingEffect {
  0% {
    stroke: rgba(255, 255, 0, 1);
    fill: rgba(0, 220, 0, 1);
  }
  100% {
    stroke: rgba(255, 255, 255, 0);
    fill: rgba(0, 0, 220, 1);
  }
}
<svg width="50" height="50" viewBox="-1 0 51 51">
  <rect class="animate" id="rect1" x="0" y="0" width="50" height="50" />
</svg>

答案 1 :(得分:1)

丢失CSS上的引号。

.animation {
    animation-name: blinking-effect;
    animation-duration: 0.5s;
    animation-iteration-count: infinite;
    animation-timing-function: ease-in-out;
    animation-direction: alternate;
}

同样由矩形重复y属性,没有宽度,我假设是一个拼写错误,动画类属性在一个空格中结束,我认为是另一个错字。