如何旋转svg图标包装在按钮点击



我正在尝试向svg添加一个css动画,它被包裹在按钮中。

模板

<button class="rotate"> 
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" width="1em" height="1em" style="-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg);" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24">
<path fill="#626262" d="M12 17a1.72 1.72 0 0 1-1.33-.64l-4.21-5.1a2.1 2.1 0 0 1-.26-2.21A1.76 1.76 0 0 1 7.79 8h8.42a1.76 1.76 0 0 1 1.59 1.05a2.1 2.1 0 0 1-.26 2.21l-4.21 5.1A1.72 1.72 0 0 1 12 17z" />
</svg>
click!
</button>

Js文件

$(".rotate").click(function(){
$(this).toggleClass("down")  ; 
});

CSS文件

.rotate {
-moz-transition: all 2s linear;
-webkit-transition: all 2s linear;
transition: all 2s linear;
}
.rotate.down {
-moz-transform: rotate(-180deg);
-webkit-transform: rotate(-180deg);
transform: rotate(-180deg);
}

您需要将点击事件目标设置为要旋转的svg。您还需要从svg中删除样式属性

document.getElementById("rotate").addEventListener("click", function() {
document.querySelector(".rotate").classList.add("down");
});
.rotate {
-moz-transition: all 2s linear;
-webkit-transition: all 2s linear;
transition: all 2s linear;
}
.rotate.down {
-moz-transform: rotate(-180deg);
-webkit-transform: rotate(-180deg);
transform: rotate(-180deg);
}
<button id="rotate"> 
<svg class="rotate" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24">
<path fill="#626262" d="M12 17a1.72 1.72 0 0 1-1.33-.64l-4.21-5.1a2.1 2.1 0 0 1-.26-2.21A1.76 1.76 0 0 1 7.79 8h8.42a1.76 1.76 0 0 1 1.59 1.05a2.1 2.1 0 0 1-.26 2.21l-4.21 5.1A1.72 1.72 0 0 1 12 17z" />
</svg>
click!
</button>

最新更新