【问题标题】:I can't understand why CSS Transition is not working on keydown [duplicate]我不明白为什么 CSS 转换在 keydown 上不起作用 [重复]
【发布时间】:2020-07-02 14:24:24
【问题描述】:

我正在尝试制作左右移动方块的动画。但我不明白为什么它不起作用。例如,它适用于点击事件。这是我的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>

【问题讨论】:

  • 使用transition: margin 0.5s ...;
  • 它适用于margin-left,我只是想为margin 使用,而不是添加所有边距属性。

标签: javascript css transition keydown


【解决方案1】:

transition 应该添加一次,这里是一个有效的 sn-p:

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>

【讨论】:

    【解决方案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);
    }
    

    【讨论】:

      【解决方案3】:

      如果你看看你写的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 的转换丢失。

      因此,要么删除第二个转换规则,要么将其编写为单个规则,将用逗号分隔属性。

      【讨论】:

        猜你喜欢
        • 2022-01-23
        • 2014-12-12
        • 2014-04-20
        • 1970-01-01
        • 2021-07-10
        • 2020-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多