3

При клике на элемент происходит анимация, но можно ли вернуть элемент в исходное состояние при повторном клике. (Сделать обратную анимацию)

const btn = document.querySelector('div[role="button"]');
const micro = document.querySelectorAll('.micro');
btn.onclick = () => {
  micro.forEach((e) => {
    e.beginElement();
  });
}
div[role="button"] {
  border: 0.0625rem solid;
  width: 68px;
  font-size: 0;
}
<div role="button">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="68" height="68" viewBox="0 0 24 24">
    <g>
    <rect id="top-part" x="9" y="3.5" width="6" height="12" rx="3" fill="#5A8CF6"/>
      <animate class="micro" xlink:href="#top-part" attributeName="height" from="12" to="6" dur="400ms" begin="indefinite" fill="freeze" />
      <animate class="micro" id="drill" xlink:href="#top-part" attributeName="y" from="3.5" to="9" begin="indefinite" dur="400ms" fill="freeze" />
    </g>
    <g stroke="#5A8CF6" fill="none">
      <g>
        <circle id="baloon" cx="12" cy="12" r="6" stroke-width="1.5" stroke-dasharray="37.7" stroke-dashoffset="18.8"/>
        <animate xlink:href="#baloon" attributeName="stroke-dashoffset" from="18.8" to="0" dur="300ms" begin="drill.end" fill="freeze"/>
      </g>
      <g>
        <rect id="leg" x="11" y="18" width="2" height="4" fill="#5A8CF6" stroke="none" transform-origin="top"/>
        <animate class="micro" xlink:href="#leg" attributeName="height" from="4" to="0" dur="400ms" begin="indefinite"  fill="freeze" />
      </g>
    </g>
  </svg>
</div>

2 ответа 2

3

Немного скорректировал SVG и добавил чуть-чуть JS. Правда, в погоне за минимальными изменениями, слегка изменилась анимация (не знаю, насколько это критично):

const btn = document.querySelector('div[role="button"]');
const micro = document.querySelectorAll('.micro');
btn.onclick = () => {
  micro.forEach((e) => {
    let sTemp = e.getAttribute('from');
    e.setAttribute('from', e.getAttribute('to'));
    e.setAttribute('to', sTemp);
    e.beginElement();
  });
}
div[role="button"] {
  border: 0.0625rem solid;
  width: 68px;
  font-size: 0;
}
<div role="button">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="68" height="68" viewBox="0 0 24 24">
    <g>
      <rect id="top-part" x="9" y="3.5" width="6" height="12" rx="3" fill="#5A8CF6"/>
      <animate class="micro" xlink:href="#top-part" attributeName="height" from="6" to="12" dur="400ms" begin="indefinite" fill="freeze" />
      <animate class="micro" id="drill" xlink:href="#top-part" attributeName="y" from="9" to="3.5" begin="indefinite" dur="400ms" fill="freeze" />
    </g>
    <g stroke="#5A8CF6" fill="none">
      <g>
        <circle id="baloon" cx="12" cy="12" r="6" stroke-width="1.5" stroke-dasharray="37.7" stroke-dashoffset="18.8"/>
        <animate class="micro" xlink:href="#baloon" attributeName="stroke-dashoffset" from="0" to="18.8" dur="400ms" begin="indefinite" fill="freeze"/>
      </g>
      <g>
        <rect id="leg" x="11" y="18" width="2" height="4" fill="#5A8CF6" stroke="none" transform-origin="top"/>
        <animate class="micro" xlink:href="#leg" attributeName="height" from="0" to="4" dur="400ms" begin="indefinite"  fill="freeze" />
      </g>
    </g>
  </svg>
</div>

1
  • Хотел уже ответ опубликовать, опередил, блин)
    – Arthur
    12 дек 2018 в 19:16
3
  • Зеленая кнопка имеет id="play" Запуск анимации от радиокнопки к иконке микрофона Красная кнопка имеет id="stop" Запуск анимации от иконки микрофона к радиокнопке
  • Заменил прямоугольник на <polyline> с атрибутом stroke-linecap="round" что позволило убрать лишние анимации.
  • Если анимация находится внутри тегов svg элементов, то не нужно писать xlink:href Эта переадресовка нужна, когда анимация находится вне анимируемых элементов.

<style>
  div[role="button"] {
    border: 0.0625rem solid;
    width: 68px;
    font-size: 0;
  }
</style>
<div role="button">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="68" height="68" viewBox="0 0 24 24">
    <polyline points="12,12 12,3.5" stroke="#5A8CF6" stroke-width="6" stroke-linecap="round">
      <animate attributeName="points" values="12,12 12,3.5;12,12 12,12" begin="stop.click" dur="0.4s" fill="freeze"/>
      <animate attributeName="points" values="12,12 12,12;12,12 12,3.5" begin="play.click" dur="0.4s" fill="freeze"/>  
    </polyline>
    <circle id="baloon" cx="12" cy="12" r="6" stroke-width="1.5" stroke="#5A8CF6" fill="none" stroke-dasharray="37.7" stroke-dashoffset="18.8">
      <animate attributeName="stroke-dashoffset" from="18.8" to="0" begin="stop.click" dur="0.3s" fill="freeze"/>
      <animate attributeName="stroke-dashoffset" from="0" to="18.8" begin="play.click" dur="0.3s" fill="freeze"/>
    </circle>
    <rect id="leg" x="11" y="18" width="2" height="4" fill="#5A8CF6" stroke="none">
      <animate attributeName="height" from="4" to="0" begin="stop.click" dur="0.3s" fill="freeze"/>
      <animate attributeName="height" from="0" to="4" begin="play.click" dur="0.3s" fill="freeze"/>
    </rect> 
    <g id="play">
      <circle  cx="4" cy="20" r="3" fill="yellowgreen"/>
    </g>
    <g id="stop">
      <circle  cx="20" cy="20" r="3" fill="crimson"/>
    </g>
  </svg>
</div>

8
  • 1
    Благодарю, как всегда помогло))
    – Arthur
    12 дек 2018 в 16:27
  • мне конечно понравилось решение но ответ не соответствует же вопросу 12 дек 2018 в 16:32
  • да это не наезд ... просто написано что при клике на элементе а в ответе при клике на два элемента получается ... это не наезд ..я тоже давно искал как можно сделать анимацию при клике два раза туда и обратно 12 дек 2018 в 16:37
  • @Alexandr_TT извените за прошлую плохую беседу ... это не злость была 12 дек 2018 в 16:42
  • 1
    @Alexandr_TT чисто SVG - это круто, но JS наше всё)) А то повадились - анимировать через CSS, а оформлять с помощью JS)))
    – UModeL
    12 дек 2018 в 19:06

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.