如何在点击时来回旋转 SVG?

How to rotate SVG back and forth on click?

所以我有这个箭头 SVG,我将其用于 hiding/displaying a div。如何在每次点击时来回旋转箭头?

Html:

<md-icon md-svg-icon="assets/svg/down-arrow.svg"></md-icon>

SVG:

<?xml version="1.0" encoding="iso-8859-1"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="arrow" x="0px" y="0px" viewBox="0 0 386.257 386.257" style="enable-background:new 0 0 386.257 386.257;" xml:space="preserve" width="24px" height="24px">
<polygon points="0,96.879 193.129,289.379 386.257,96.879 " fill="#e18327"/>
</svg>

使用CSS 转换和JavaScript 非常简单。使用 JS 监听点击事件,当它发生时切换 class(其中有 CSS transform: rotate)打开或关闭。

在下面的代码片段中,我使用了内联 SVG(即 md-icon 标记内的 SVG,因为 SVG 文件未托管到 link 的任何地方),但您可以这样做这也与外部 SVG 文件有关。只需添加侦听器并将 class 设置为 md-icon 元素或任何包含 SVG 的元素。

document.querySelector('md-icon').addEventListener('click', function() {
  this.classList.toggle('rotated');
});
.rotated {
  transform: rotate(-90deg);
}
md-icon {
  display: inline-block;
  transition: all 1s;
}
<link href="http://rawgit.com/angular/bower-material/master/angular-material.min.css" rel="stylesheet"/>
<md-icon md-svg-icon='assets/svg/down-arrow.svg'>
  <?xml version="1.0" encoding="iso-8859-1" ?>
  <!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="arrow" x="0px" y="0px" viewBox="0 0 386.257 386.257" style="enable-background:new 0 0 386.257 386.257;" xml:space="preserve" width="24px" height="24px">
    <polygon points="0,96.879 193.129,289.379 386.257,96.879 " fill="#e18327" />
  </svg>
</md-icon>

我们当然可以使用两个不同的 SVG 文件并在单击时更改源(从向下箭头到向右箭头),但这不会像下面的代码片段那样产生平滑的过渡。

另一种选择是使用 SMIL 动画,但它们已被弃用,因此最好使用 CSS 转换。