【问题标题】:Synchronize animation in SVG elements using CSS使用 CSS 同步 SVG 元素中的动画
【发布时间】:2014-12-15 17:11:49
【问题描述】:

我正在尝试使用以下 CSS 创建一个简单的闪烁 SVG 元素:

.led-red-blink {
    animation-name: grey-red;
    animation-duration: 1s;
    animation-iteration-count: infinite;
    stroke-width: 1;
    stroke: #808080;
}
.led-red-blink:hover {
    animation-name: grey-red;
    animation-duration: 1s;
    animation-iteration-count: infinite;
    stroke-width: 1;
    stroke: #efefef;
}

@keyframes grey-red {
    0% { fill: #808080; }
    50% { fill: #EE5544; }
    100% { fill: #808080; }
}
.led-green-blink {
    /* just like led-red-blink */
}

以及 UI 元素(为清楚起见,移除了宽度、高度、x、y):

<rect class="led-red-blink" id="led-h1"></rect>
<rect class="led-green" id="led-ok"></rect>

动画本身可以正常工作,但如果我将 led-red-blink 类分配给另一个 rect 对象,它们会不同步闪烁。 rects 的类可以随时更改。

如何同步所有矩形对象的动画同时发生? IE。每当 rect 的类发生更改时,每个 rect 动画的开始时间都是相同的,而不是发生更改时。

【问题讨论】:

    标签: css svg


    【解决方案1】:

    将 svg 元素分组到一个 g 标记中,为其分配一个类并使用该类来应用动画。

    像这样 -> jsfiddle

    <svg height="100" width="300">
        <g class="circles">
      <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
        <circle cx="200" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
        </g>
    </svg>
    
    g.circles {
        -webkit-animation: move 3s linear infinite;
    }
    @-webkit-keyframes move {
        0%{
            opacity:1;
        }
        100%{
            opacity:0;
        }
    }
    

    【讨论】:

    • 感谢您的解决方案。我唯一的问题是,有了这个,对象会出现和消失,而不是在两个特定的外观之间切换。我已经通过首先添加背景图像解决了这个问题,但这需要两个对象。有更好的解决方案吗?
    • 您可以使用 jQuery 在 g 元素上切换动画类,而不是我之前的解决方案。这可能是一个更好的解决方案。当我到达我的电脑并回复你时,我会准备一个 jsfiddle :)
    • 查看这个jsfiddle 注意,我们需要在将类归因于 svg 元素时使用 attr。代码的 setTimeout 部分“重置”您的动画,以便您可以多次运行它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 2011-06-17
    • 2014-02-02
    • 2022-01-05
    • 2016-02-06
    • 1970-01-01
    相关资源
    最近更新 更多