Как заставить анимацию CSS воспроизводиться вперед или назад по требованию - PullRequest
0 голосов
/ 29 августа 2018

У меня есть анимация CSS, которая в зависимости от некоторой ситуации я хочу иметь возможность переключаться вперед или назад в любое время на основе некоторых JS. Вот базовый пример:

HTML

<div id="box"></div>
<button onclick="toggle()">toggle</button>

JS

window.isSmall = true;
window.toggle = function() {
    if (isSmall) {
    var el = document.getElementById("box");
    el.classList.add("bigger");
  } else {
    // ????
  }
  isSmall = !isSmall;
}

1009 * CSS *

@keyframes bigger {
    from { width:100px; height:100px; }
    to { width:200px; height:200px; }
}

#box {
    width:100px;
    height:100px;
    background-color: red;
}

.bigger {
    animation-name: bigger;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}

Fiddle: http://jsfiddle.net/gbh408up/

Я думал, что это будет довольно просто, но удивительно, что я не смог найти метод для достижения этой цели. Обратите внимание, я специально ищу решение с анимацией, а не с переходами. Есть идеи?

Ответы [ 2 ]

0 голосов
/ 30 августа 2018

Я только что понял это. Итак, вот мое решение:

<div id="box"></div>

<button onclick="toggle()">toggle</button>

window.isSmall = true;
window.toggle = function() {
    var el = document.getElementById("box");
    if (el.className == "a") {
    el.className = "b";
    } else {
    el.className = "a";
  }
  isSmall = !isSmall;
  console.log('toggle');
 }


@keyframes a {
    from { width:100px; height:100px; }
    to { width:200px; height:200px; }
}
@keyframes b {
    from { width:200px; height:200px; }
    to { width:100px; height:100px; }
}

#box {
    width:100px;
    height:100px;
    background-color: red;
}

.a {
    animation-name: a;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}
.b {
  animation-name: b;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}

Я изменил «больше» на «а», а «меньше» на «б». Но это работает. Хорошо, у меня это сейчас на скрипке.

https://jsfiddle.net/markem/2b6n3gmc/1/

Кроме того, на этот вопрос несколько вопросов ответили здесь, в StackOverflow:

Javascript просто добавить класс удалить класс

0 голосов
/ 29 августа 2018

Вы можете работать с 2 классами, которые анимируют то, что требуется.

window.isSmall = true;
window.toggle = () => {
  const box = document.getElementById("box");
  if (isSmall) {
    box.classList.remove("smaller");
    box.classList.add("bigger");
  } else {
    box.classList.remove("bigger");
    box.classList.add("smaller");
  }
  isSmall = !isSmall;
  console.log(isSmall)
}
@keyframes bigger {
  from {
    width: 100px;
    height: 100px;
  }
  to {
    width: 200px;
    height: 200px;
  }
}

@keyframes smaller {
  from {
    width: 200px;
    height: 200px;
  }
  to {
    width: 100px;
    height: 100px;
  }
}

#box {
  width: 100px;
  height: 100px;
  background-color: red;
}

.bigger {
  animation-name: bigger;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}

.smaller {
  animation-name: smaller;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}
<div id="box"></div>
<button onclick="toggle()">toggle</button>
...