单击SVG时反转动画效果?

Reverse animation effect when SVG is clicked?

我有一个很酷的 pause/resume 变形动画,它是我从新的 YouTube 嵌入播放器中获得灵感而制作的。无论如何,如果您加载页面,您可以看到 SVG 变形工作得很好......并且您可以通过更改标签中的 "from" 和 "to" 属性来更改变形。但我想做的是在单击“.ytp-play-button”时使用 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"
   });
});

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

  1. Create the <animation> with begin="indefinite" so that it won't treat the animation as starting on document load. You can do this either via JavaScript or raw SVG source.
  2. Call beginElement() on the SVGAnimationElement instance (the <animate> element) when you're ready for the animation to start. For your use case, use a standard addEventListener() callback to invoke this method when you're ready

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

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>