先构造出向下箭头的 html:
<svg class="icon icon-arrow" onclick="rotateArrow()">
<symbol id="icon-arrow" viewBox="0 0 1024 1024">
<title>down</title>
<path d="M771.512499 509.49597 511.614214 959.653483 251.715929 509.49597 414.441057 509.49597 414.441057 64.132646 608.786347 64.132646 608.786347 509.49597Z" p-id="982"></path>
</symbol>
<use xlink:href="#icon-arrow"></use>
</svg>
css 设置翻转动画:
.icon-arrow {
width: 100px;
height: 100px;
/*设置所有动画的效果:0.3s 淡出效果*/
transition: all .3s ease-out;
}
.icon-arrow-rotate {
/*旋转180度*/
transform: rotate(180deg);
}
js 点击事件,添加 / 移除旋转动画:
当 rotFlag 为 true 时,添加 icon-arrow-rotate 类;否则移除;
由于一开始的箭头不应该自动旋转,所以不添加 icon-arrow-rotate 类,因此 rotFlag 应初始化为 true。
每一次点击事件后反置 rotFlag,使得每一次的点击都能翻转。
let rotFlag = true;
let element = document.querySelector(".icon-arrow");
let rotateArrow = () => {
if(rotFlag) {
element.classList.add("icon-arrow-rotate");
}else {
element.classList.remove("icon-arrow-rotate");
}
rotFlag = !rotFlag;
};
在 icon-arrow 而不是 icon-arrow-rotate 中设置 transition 是因为:这里只在有 icon-arrow-rotate 的时候才设置翻转,如果移除 icon-arrow-rotate,会失去返回向下箭头的效果,在 icon-arrow 中设置可以防止这种情况出现。
点个赞鼓励一下~