简体   繁体   English

SVG可变值上的动画不透明度

[英]SVG Animate Opacity on Variable Value

I am trying to animate an svg element to disappear (slowly and gracefully) when a binary variable is set to zero and then reappear (again, nice and slow) when the binary variable is back to one. 我正在尝试为svg元素设置动画,以在二进制变量设置为零时消失(缓慢而优雅地),然后在二进制变量恢复为一时重新出现(再次,良好且缓慢)。 I have the image disappearing, but cant seem to figure out haw to get it to reappear. 我的图像消失了,但似乎无法弄清楚如何使其重新出现。 Here is the JavaScript: 这是JavaScript:

function go() {

    var max = 2;
    var random = Math.floor(Math.random() * Math.floor(max));;
    console.log("hi" + random);

    var elements = document.getElementsByTagName("animate");
    for (var i = 0; i < elements.length; i++) {
        if (random == 1) {
            elements[i].beginElement();
        }
        else {
            elements[i].endElement();

        }

    }
}

and here is the SVG elements 这是SVG元素

  <svg xmlns="http://www.w3.org/2000/svg" class="icons" width="40" height="40">
<g class="icon" transform="translate(-2 -2)">
  <path class="icon__sight" d="M38.255 20.182A16.353 16.353 0 0 0 23.818 5.745V2h-3.636v3.745A16.353 16.353 0 0 0 5.745 20.182H2v3.636h3.745a16.353 16.353 0 0 0 14.437 14.437V42h3.636v-3.745a16.353 16.353 0 0 0 14.437-14.437H42v-3.636h-3.745zM22 34.727A12.727 12.727 0 1 1 34.727 22 12.718 12.718 0 0 1 22 34.727z" fill="#fff"/>
  <circle class="icon__indicator" cx="8" cy="8" r="8" transform="translate(14 14)" fill="#88db29">
    <animate dur="1" attributeName="opacity" from="1" to="0" begin="move.end" repeatCount="0" fill="freeze" />
  </circle>/>
</g>

Any tips or advice is greatly appreciated. 任何提示或建议,不胜感激。 Be kind, I am new to this :) 友善,我是新来的:)

This seems overly complicated for simply transitioning the opacity of the SVG. 对于仅过渡SVG的不透明度而言,这似乎过于复杂。 Why not utilize CSS to transition the state with manipulating the class via your JS? 为什么不利用CSS通过JS操作类来转换状态呢?

svg {
  transition: opacity 0.5s ease;
}

svg.hidden {
  opacity: 0;
}
var svg = document.querySelector('svg');
...
        if (random == 1) {
            svg.classList.remove('hidden');
        }
        else {
            svg.classList.add('hidden');

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM