键盘控制Div的移动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>事件对象-通过键盘控制div运动</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<style type="text/css">
*{margin: 0px; padding: 0px; font-size:14px; font-family:‘微软雅黑‘;}
.clearfix:after{content:‘.‘;display:block;height:0;clear:both;visibility:hidden}
.clearfix{display:inline-block;}
* html .clearfix{height:1%}
.clearfix{display:black;}
#box{width:100px;height:100px;background:red;position:absolute;}
</style>
</head>
<body>
<div id=‘box‘></div>
</body>
<script type="text/javascript">
window.onload=function(){
  var oDiv =document.getElementById(‘box‘);
  document.onkeydown = function(ev){
      var Event = ev||event;
      var L = oDiv.offsetLeft;
      var T = oDiv.offsetTop;
      //alert(Event.keyCode);
      //←37↑38→39↓40
      if(Event.keyCode==37){
        if(L<=0){
           L = 0;
        }else{
          oDiv.style.left = oDiv.offsetLeft-10+‘px‘;
        }    
      }else if(Event.keyCode==38){
        if(T<=0){
           L=0;
        }else{
          oDiv.style.top = oDiv.offsetTop-10+‘px‘
        }
      }else if(Event.keyCode==39){
        if(L>=document.documentElement.clientWidth-oDiv.offsetWidth){
           L=document.documentElement.clientWidth-oDiv.offsetWidth;
        }else{
          oDiv.style.left = oDiv.offsetLeft+10+‘px‘;
        }
      }else if(Event.keyCode==40){
        if(T>=document.documentElement.clientHeight-oDiv.offsetHeight){
           T=document.documentElement.clientHeight-oDiv.offsetHeight;
        }else{
          oDiv.style.top = oDiv.offsetTop+10+‘px‘;
        }
      }  
  }
}
</script>
</html>

鼠标事件:
clientX 是可视区的横坐标
clientY 是可视区的纵坐标
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft||document.body.scrollLeft;
document.documentElement.clinetWidth 可视区的宽
document.documentElement.clinetHeight 可视区的高
键盘事件
onkeydown
onkeyup
keyCode-检测鼠标数字
Event = ev||event;
Event.keyCode 用法

 

键盘控制Div的移动,布布扣,bubuko.com

键盘控制Div的移动

上一篇:Android中属性动画Property Animation使用示例(四)


下一篇:微信公众账号开发教程