1

所以我有这个箭头 SVG,我用它来隐藏/显示一个 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>
4

1 回答 1

3

使用 CSS 转换和 JavaScript 非常简单。transform: rotate使用 JS 来监听 click 事件,并在它发生时打开或关闭一个类(具有 CSS )。

在下面的代码片段中,我使用了内联 SVG(也就是说,md-icon标签中的 SVG,因为 SVG 文件没有托管在任何可链接的地方),但您也可以使用外部 SVG 文件来做到这一点。只需添加侦听器并将类设置为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 转换。

于 2016-06-03T03:58:26.120 回答