我不明白为什么CSS Transition无法在按键上起作用

问题描述 投票:1回答:3

我正在尝试制作动画,以将块向右和向左移动。但是我不明白为什么它不起作用。例如,它非常适合单击事件。这是我的codepen。谢谢

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>
javascript css transition keydown
3个回答
2
投票

cssCSS中有两个transition实例

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

如果要在左边距左边距和顶部右边距之间有不同的过渡,可以将它们组合。

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

2
投票

过渡应该添加一次,这是一个有效的代码段:

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 0.5s cubic-bezier(0, .7, 0, 1);
}

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

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

1
投票

如果您查看已编写的css,则>

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

您有2个过渡属性,过渡属性被下一个覆盖,即下一个过渡margin-top属性。

计算样式时,这就是css规则的样子。

.box {
  background-color: gray;
  height: 100px;
  width: 100px;
  transition: margin-top 0.5s cubic-bezier(0, .7, 0, 1);
}

由于具有相同类型的键,因此在margin-top的此转换中,最后一个规则将获胜,而margin-left的转换将丢失。

因此,删除第二个过渡规则或将其写为单个规则,将用逗号分隔属性。

© www.soinside.com 2019 - 2024. All rights reserved.