代码之家  ›  专栏  ›  技术社区  ›  mistkaes

单击SVG时反转动画效果?

  •  2
  • mistkaes  · 技术社区  · 9 年前

    我有一个很酷的暂停/恢复变形动画,这是我从新的YouTube嵌入播放器中得到的灵感。无论如何,如果您加载页面,您可以看到SVG变形工作得非常好…并且可以通过更改标记中的“from”和“to”属性来更改变形。但我想做的是,当单击“.ytp播放按钮”时,用jQuery编辑这些属性,但由于某种原因,它不起作用,有什么帮助吗?

    代码演示: http://codepen.io/mistkaes/pen/jPdWMe

    全页演示: http://s.codepen.io/mistkaes/debug/jPdWMe

    jQuery:

    $(".ytp-play-button").click(function() {
       $("#ytp-12").attr({
        "from": "M11,10 L18,13.74 18,22.28 11,26 M18,13.74 L26,18 26,18 18,22.28",
        "to": "M11,10 L17,10 17,26 11,26 M20,10 L26,10 26,26 20,26"
       });
    });
    
    1 回复  |  直到 9 年前
        1
  •  4
  •   Community CDub    7 年前

    您所拥有的动画被定义为仅在页面加载时运行一次。在一个 different answer ,它解释了如何在需要时运行SVG动画。

    1. 创建 <animation> 具有 begin="indefinite" 因此它不会将动画视为在加载文档时开始。您可以通过JavaScript或原始SVG源代码执行此操作。
    2. 呼叫 beginElement() SVGAnimationElement 实例( <animate> 元素)。对于您的用例,使用标准 addEventListener() 准备好后调用此方法的回调

    将此逻辑应用于代码,这是一个有效的解决方案,它利用一个额外的变量在两种形状之间切换:

    var flip = true,
        pause = "M11,10 L18,13.74 18,22.28 11,26 M18,13.74 L26,18 26,18 18,22.28",
        play = "M11,10 L17,10 17,26 11,26 M20,10 L26,10 26,26 20,26",
        $animation = $('#animation');
    
    $(".ytp-play-button").on('click', function(){
        flip = !flip;
        $animation.attr({
            "from": flip ? pause : play,
            "to": flip ? play : pause
        // .get(0) is used to get the native DOM element
        // [0] would also work
        }).get(0).beginElement();
    });
    html {
        background-color: #1c1c1f;
    }
    
    button {
        outline: none;
        border: 0px solid;
        background: transparent;
    }
    
    .ytp-play-button {
        fill: #fff;
        opacity: 0.85;
        height: 175px;
    }
    
    .ytp-play-button:hover {
        cursor: pointer;
        opacity: 1;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <button class="ytp-play-button ytp-button" aria-live="assertive" tabindex="32" aria-label="Pause">
       <svg width="100%" height="100%" viewBox="0 0 36 36" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
          <defs>
             <path id="ytp-12" d="M 11 10 L 17 10 L 17 26 L 11 26 M 20 10 L 26 10 L 26 26 L 20 26">
                <animate id="animation" begin="indefinite" attributeType="XML" attributeName="d" fill="freeze" from="M11,10 L17,10 17,26 11,26 M20,10 L26,10 26,26 20,26" to="M11,10 L18,13.74 18,22.28 11,26 M18,13.74 L26,18 26,18 18,22.28" dur="1.1s" keySplines=".4 0 1 1" repeatCount="1"></animate>
             </path>
          </defs>
          <use xlink:href="#ytp-12" class="ytp-svg-shadow"></use>
          <use xlink:href="#ytp-12" class="ytp-svg-fill"></use>
       </svg>
    </button>