Как повернуть значок svg, завернутый в кнопку, при нажатии?

#javascript #html #css #css-animations

Вопрос:

Я пытаюсь добавить css-анимацию в svg, которая завернута внутри кнопки.

Шаблон

 <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);
}
 

Комментарии:

1. Вы пытаетесь повернуть кнопку или svg внутри? Прямо сейчас вы нацелены на всю кнопку, которую нужно повернуть.

Ответ №1:

Вам нужно сделать событие щелчка целевым 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>