Je ne comprends pas pourquoi la transition CSS ne fonctionne pas sur keydown

Jaroslav Tereshchuk:

Je suis en train de faire de l' animation pour le bloc en mouvement vers la droite et vers la gauche. Mais je ne comprends pas pourquoi cela ne fonctionne pas. Par exemple, il fonctionne bien pour un événement de clic. Voici mon codepen . Merci

const box = document.getElementsByClassName('box')[0];

document.addEventListener('keydown', function({
  keyCode,
  which
}) {
  const keycode = keyCode ? keyCode : which;
  switch (keycode) {
    case (39):
      box.classList.add('move-right');
      box.classList.remove('move-left');
      break;
    case (37):
      box.classList.add('move-left');
      box.classList.remove('move-right');
      break;
  }
});
.box {
  background-color: gray;
  height: 100px;
  width: 100px;
  transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1);
  transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}

.move-right {
  margin-left: 400px;
}

.move-left {
  margin-left: 0px;
}
<div class="box"></div>

Koralarts:

Vous avez deux instances de transitionvotre cssCSS

.box {
  ...
  transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1);
  transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}

Si vous voulez avoir spécifiquement différentes transitions entre la marge gauche et la marge supérieure, vous pouvez les combiner.

.box {
  ...
  transition: margin-left 0.5s cubic-bezier(0, .7, 0, 1), margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}

Je suppose que tu aimes

Origine http://43.154.161.224:23101/article/api/json?id=347056&siteId=1
conseillé
Classement