用JS写一个可以用键盘方向键控制的动画:
效果如下:
好了,代码如下:
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< meta http-equiv = "X-UA-Compatible" content = "ie=edge" >
< title >Document</ title >
< style >
body {
overflow: hidden
}
img {
position: absolute;
top: 0;
left: 10px;
width: 100px;
height: 82px
}
.right {
transform: rotateY(180deg)
}
.top {
transform: rotateZ(45deg)
}
.bottom {
transform: rotateZ(-45deg)
}
</ style >
</ head >
< body >
< img src = "./img//Blue ocean11.png" alt = "" class = "move-background" >
< script >
var oImg = document.querySelector("img");
/* 思路: */
/* 监听键盘的事件(<- -> 上 下) */
document.onkeydown = function(e) {
e = e || window.event;
var code = e.which || e.keyCode;
var offset = 10;
switch (code) {
case 37:
console.log("left");
console.log('innerWidth',innerWidth,oImg.offsetLeft);
oImg.className = "";
var left = oImg.offsetLeft - offset;
if (left <= -oImg.offsetWidth) {
left = window.innerWidth;
}
oImg.style.left = left + "px";
break;
case 38:
console.log("top");
oImg.className = "top";
var top = oImg.offsetTop - offset;
if (top <= -oImg.offsetHeight) {
top = window.innerHeight;
}
oImg.style.top = top + "px";
break;
case 39:
console.log("right");
oImg.className = "right";
var left = oImg.offsetLeft + offset;
if (left >= window.innerWidth) {
left = -oImg.offsetWidth;
}
oImg.style.left = left + "px";
break;
case 40:
console.log("bottom");
oImg.className = "bottom";
var top = oImg.offsetTop + offset;
if (top >= window.innerHeight) {
top = -oImg.offsetHeight;
}
oImg.style.top = top + "px";
break;
default:
break;
}
/* 临界值检查 */
}
</ script >
</ body >
</ html >
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Frank_yzb123123/article/details/111030177