首页 > 代码库 > 页面上有一个div 100*100 颜色为黄色 按键盘上下左右键可以操作div移动 ctrl+键盘上下键可以放大缩小 ctrl+键盘左右键可以随机变颜色

页面上有一个div 100*100 颜色为黄色 按键盘上下左右键可以操作div移动 ctrl+键盘上下键可以放大缩小 ctrl+键盘左右键可以随机变颜色

 1 <body>
 2 <div id="w">
 3     <div class="n">按上键可以向上移动</div>
 4     <div class="n">按下键可以向下移动</div>
 5     <div class="n">按左键可以向左移动</div>
 6     <div class="n">按右键可以向右移动</div>
 7     <div class="n">ctrl+键盘上键可以放大</div>
 8     <div class="n">ctrl+键盘下键可以缩小</div>
 9     <div class="n">ctrl+键盘左右键可以随机变颜色</div>
10     <div id="box" style="width: 100px;height: 100px;background-color: #ff0;position: absolute;left: 100px;top: 100px; z-index: -1"></div>
11 </div>
12 <script>
13     var box = document.getElementById(‘box‘);
14     document.body.addEventListener(‘keydown‘, function (e) {
15         switch (e.keyCode) {
16             case 37:
17                 if (e.ctrlKey) {
18                     box.style.backgroundColor = ‘#‘ + (Math.random().toString(16)).substr(-6);
19                 } else {
20                     box.style.left = parseInt(box.style.left) - 6 + ‘px‘;
21                 }
22                 break;
23             case 39:
24                 if (e.ctrlKey) {
25                     box.style.backgroundColor = ‘#‘ + (Math.random().toString(16)).substr(-6);
26                 } else {
27                     box.style.left = parseInt(box.style.left) + 6 + ‘px‘;
28                 }
29                 break;
30             case 38:
31                 box.style.top = parseInt(box.style.top) - 6 + ‘px‘;
32                 if (e.ctrlKey) {
33                     box.style.width = parseInt(box.style.width) + 4 + ‘px‘;
34                     box.style.left = parseInt(box.style.left) - 2 + ‘px‘;
35                     box.style.height = parseInt(box.style.height) + 4 + ‘px‘;
36                     box.style.top = parseInt(box.style.top) + 4 + ‘px‘;
37                 }
38                 break;
39             case 40:
40                 box.style.top = parseInt(box.style.top) + 6 + ‘px‘;
41                 if (e.ctrlKey) {
42                     box.style.width = parseInt(box.style.width) - 4 + ‘px‘;
43                     box.style.left = parseInt(box.style.left) + 2 + ‘px‘;
44                     box.style.height = parseInt(box.style.height) - 4 + ‘px‘;
45                     box.style.top = parseInt(box.style.top) - 4 + ‘px‘;
46                 }
47                 break;
48         }
49         console.log(e.keyCode);
50     })
51 </script>
52 </body>

 

页面上有一个div 100*100 颜色为黄色 按键盘上下左右键可以操作div移动 ctrl+键盘上下键可以放大缩小 ctrl+键盘左右键可以随机变颜色