📜  如何在javascript代码示例中使用箭头键移动图像

📅  最后修改于: 2022-03-11 15:02:17.860000             🧑  作者: Mango

代码示例1
//HTML document

  
  Moving image


    
    


//Javascript

//getting the image node
const movingImage = document.querySelector('#movingImage');

//when the user presses any key, the 'document.body.onkeydown' function is called
//move the image inside that function
document.body.onkeydown = (e) => {
  //handle the moving of image
  //e has a property called key which states the name of the key pressed
  
  switch(e.key){
    case 'ArrowUp':
      movingImage.offsetTop--;
      break;
      case 'ArrowLeft':
      movingImage.offsetLeft--;
      break;
      case 'ArrowRight':
      movingImage.offsetTop++;
      break;
      case 'ArrowDown':
      movingImage.offsetLeft++-;
      break;
  }
}