方向键控制小球运动

"Hello World, Hello Blog"

Posted by wudimingwo on December 15, 2018
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
59
60
<html>
	<head>
	  <meta charset="UTF-8"/>
		<title>回顾第一遍</title>
    <style type="text/css">
    	.box,.demo{
    	  width: 100px;
    	  height: 100px;
    	  background: radial-gradient(pink 0%,purple 100%);
    	  border-radius: 50%;
    	  position: absolute;
    	  left: 0;
    	  top: 0;
    	  box-shadow: 0px 0px 4px 1px black,0px 0px 4px 1px black inset;
    	}
    </style>		
	</head>
	<body>
	  
		<div class="box"></div>
		
		
		<script type="text/javascript">

        //控制小球运动
        var oBox = document.getElementsByClassName('box')[0];
        var speedx = 5;
        var speedy = 5;
        document.onkeydown = function (e) {
        	switch (e.which){
        		case 38:
        		    speedy--;
        			break;
        		case 40:
        		    speedy++;
        			break;
        		case 37:
        		    speedx--;
        			break;
        		case 39:
        		    speedx++;
        			break;
        		default:
        			break;
        	}
        	}
        	oBox.onclick = function () {
        	  
        		this.timer = setInterval(function () {
        			oBox.style.left = oBox.offsetLeft + speedx + 'px';
        			oBox.style.top = oBox.offsetTop + speedy + 'px';
        			
        		},50);
        	}


		</script>
		
	</body>
</html>