0
点赞
收藏
分享

微信扫一扫

键盘的按键事件

捡历史的小木板 2022-01-17 阅读 140

1. 键盘的按键事件

2.键盘事件的事件对象

3.案例:通过键盘上下左右控制标签移动

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    div {
      width: 600px;
      height: 600px;
      padding: 100px;
      border: 20px solid paleturquoise;
      background: rgb(160, 241, 160);
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 200px auto;
      position: relative;
    }
    p {
      width: 50px;
      height: 50px;
      padding: 50px;
      border: 10px solid orange;
      background: pink;
      position: absolute;
    }
  </style>
</head>
<body>
  <div>
    <p></p>
  </div>

  <script>
    //获取标签对象
    var oDiv = document.querySelector('div');
    var oP = document.querySelector('p');

    //获取父级占位(内容+padding)
    let oDivWidth = oDiv.clientWidth;
    let oDivHeight = oDiv.clientHeight;
    //获取子级占位(内容+padding+border)
    let oPWidth = oP.offsetWidth;
    let oPHeight = oP.offsetHeight;

    //给整个document绑定事件
    document.addEventListener('keydown', function (e) {
      //键盘按键编号是 37 证明点击的是 向左按键
      if (e.keyCode === 37) {
        //按下的是左按键 需要 p标签向左定位移动
        //获取当前标签 left 定位数值
        let oPLeft = parseInt(window.getComputedStyle(oP).left);
        //累减 设定的步长值
        oPLeft -= 5;
        //设置最小值
        oPLeft = oPLeft < 0 ? 0 : oPLeft;
        //将 新的数值 作为定位属性的属性值
        oP.style.left = oPLeft + 'px';

      } else if (e.keyCode === 38) {
        let oPTop = parseInt(window.getComputedStyle(oP).top);
        oPTop -= 5;
        oPTop = oPTop < 0 ? 0 : oPTop
        oP.style.top = oPTop + 'px';

      } else if (e.keyCode === 39) {
        let oPLeft = parseInt(window.getComputedStyle(oP).left);
        oPLeft += 5;
        oPLeft = oPLeft > oDivWidth - oPWidth ? oDivWidth - oPWidth : oPLeft;
        oP.style.left = oPLeft + 'px';

      } else if (e.keyCode === 40) {
        let oPTop = parseInt(window.getComputedStyle(oP).top);
        oPTop += 5;
        oPTop = oPTop > oDivHeight - oPHeight ? oDivHeight - oPHeight : oPTop;
        oP.style.top = oPTop + 'px';
      }
    })
  </script>
</body>
</html>
举报

相关推荐

0 条评论