【代码】漂浮图片效果

前言

图片在页面中漂浮,遇到边界反弹
运动轨迹类似于_WindowsXP的屏幕保护_和_打砖块小游戏_

源代码

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>

* {
margin: 0;
padding: 0;
}

.cur {
position: relative;
width: 200px;
height: 200px;
background: url("img/fire-fox-logo.png");
background-size: 200px 200px;
}

</style>
</head>
<body>

<div class="cur"></div>

</body>
</html>
<script>

let div = document.querySelector(".cur");
let l = 0;
let t = 0;
let status = 0;

// 开启定时器
setInterval(
function () {

// 调用运动函数
move(status);

// 运动算法
if ((t >= 600 && status == 0) || (l >= 800 && status == 1) || (t <= 0 && status == 2)) {
status += 1;
} else if (l <= 0 && status == 3) {
status = 0;
}
if ((t >= 600 && status == 3) || (l <= 0 && status == 2) || (t <= 0 && status == 1)) {
status -= 1;
} else if (l >= 800 && status == 0) {
status = 3;
}

div.style.left = l + "px";
div.style.top = t + "px";

},
10 // 运动间隔10ms
)

/**
* 编写一个运动函数
* @param direction 方向
* 0:右下方向
* 1:右上方向
* 2:左上方向
* 3:左下方向
*/
function move(direction) {
if (direction == 0) {
l += 5;
t += 5;
}
if (direction == 1) {
l += 5;
t -= 5;
}
if (direction == 2) {
l -= 5;
t -= 5;
}
if (direction == 3) {
l -= 5;
t += 5;
}

}

</script>

完成

参考文献

哔哩哔哩——web前端小清风