js实现用键盘控制DIV上下左右+放大缩小与变色

js 键盘按键控制小方块

用键盘控制DIV,红色方块为键盘操作区域,您可以进行如下操作:左右控制;背景变为绿色;背景变为黄色;背景变为蓝色放大或缩小
用键盘控制DIV,红色方块为键盘操作区域,您可以进行如下操作:
  上:↑ 下:↓ 左:← 右:→
  Ctrl + 1 : 背景变为绿色
  Ctrl + 2 : 背景变为黄色
  Ctrl + 3 : 背景变为蓝色
  Ctrl + ↑ : 放大
  Ctrl + ↓ : 缩小

<!--
Author: XiaoWen
Create a file: 2017-01-10 19:00:30
Last modified: 2017-01-12 13:19:28
Start to work:
Finish the work:
Other information:
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    #box{
      width:80px;
      height:80px;
      background:#f00;
      position:absolute;
    }
  </style>
</head>
<body>
<pre>
  移动:上↑ 下↓ 左← 右→
  颜色:
    ctrl + 1  绿色
    ctrl + 2  黄色
    ctrl + 3  蓝色
  大小:
    ctrl + ↑  放大
    ctrl + ↓  缩小
  <!-- 重置:Ctrl + Enter -->
</pre>
<div id="box"></div>
</body>
<script>
  var box=document.getElementById('box');
  onkeydown=function(){
    if(ev(event).ctrlKey){
      var code=ev(event).keyCode
      code==49 ? box.style.background='#0f0' : ''
      code==50 ? box.style.background='#ff0' : ''
      code==51 ? box.style.background='#00f' : ''
      code==38 ? resize('big') : ''
      code==40 ? resize('small') : ''
      code==13 ? console.log('重置') : ''
      function resize(re){
        switch(re){
          case 'big':
            box.style.width=box.offsetWidth+10+'px';
            box.style.height=box.offsetHeight+10+'px';
            break
          case 'small':
            box.style.width=box.offsetWidth-10+'px';
            box.style.height=box.offsetHeight-10+'px';
            break
        }
      }
    }else{
      var code=ev(event).keyCode
      code==37 ? box.style.left=box.offsetLeft-10+'px' : ''
      code==38 ? box.style.top=box.offsetTop-10+'px' : ''
      code==39 ? box.style.left=box.offsetLeft+10+'px' : ''
      code==40 ? box.style.top=box.offsetTop+10+'px' : ''
    }

  }
  function ev(ev){
    var e=ev||event;
    return e
  }
</script>
</html>

本来想写个函数用用的,但后面好像发现用不上。不知是没写好还是真用不上。

  function iskey(ev,code){
    // 检测用户是否按下了指定键码
    // 返回值: boolean
    // ev   : event
    // code : 键码
    // 例   : 用户是否按下数字1(主键盘区)
    //      :onkeydown=function(){console.log(iskey(event,49))}
    var e=ev||event;
    if(e.keyCode==code){
      return true
    }else{
      return false
    }
  }
View Code
原文地址:https://www.cnblogs.com/daysme/p/6277834.html