Div仅在第二次单击键时转换吗?

问题描述

我有一个黄色的div,当单击相应的键时,它会向左/向上移动。我希望它每次都过渡。发生这种情况,但是从第二次单击开始。第一次单击时,它会移动,但是没有过渡...我的代码有什么问题?

.counter {
  border-radius: 50%;
  width: 20px;
  height: 20px;
  position: absolute;
  margin-top: -100px;
  margin-left: 60px;
  transition: top linear 1s,left linear 1s;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  padding: 20px;
}

#yellow {
  background-color: yellow;
}
<div class="counter" id="yellow">P1</div>
document.onkeydown = detectKey;

function detectKey(e) {

  var posLeft = document.getElementById('yellow').offsetLeft
  var posTop = document.getElementById('yellow').offsetTop

  if (e.keyCode == '39') {
    document.getElementById('yellow').style.left = (posLeft + 80) + "px"
  }
  if (e.keyCode == '38') {
    document.getElementById('yellow').style.top = (posTop - 50) + "px"
  }
}

解决方法

我认为您只需要在CSS中指定一个初始的top和left值即可。 请参阅附件中的片段。

document.onkeydown = detectKey;

function detectKey(e) {

  var posLeft = document.getElementById('yellow').offsetLeft
  var posTop = document.getElementById('yellow').offsetTop

  if (e.keyCode == '39') {
    document.getElementById('yellow').style.left = (posLeft + 80) + "px"
  }
  if (e.keyCode == '38') {
    document.getElementById('yellow').style.top = (posTop - 50) + "px"
  }
}
.counter {
  border-radius: 50%;
  width: 20px;
  height: 20px;
  position: absolute;
  /*margin-top:-100px;
   margin-left:60px;*/
  transition: top linear 1s,left linear 1s;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  padding: 20px;
  top: 0; /* <<< */
  left: 0; /* <<< */
}

#yellow {
  background-color: yellow;
}
<div class="counter" id="yellow">P1</div>