本文实例为大家分享了JavaScript实现多球运动的具体代码,供大家参考,具体内容如下
代码如下:
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
|
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title >多球运动</ title >
< style >
*{margin:0;padding:0;}
body{background-color: #90f;}
.ball{position: absolute;left:0;top:0;width:100px;height:100px;background: #f0f;border-radius: 50%;}
</ style >
</ head >
< body >
< script >
run(22)//封装
//定义速度
var speed;
function run(num){
//创建出num个div
for(var i=0;i< num ;i++){
//[2,11) 随机速度
speed = Math .floor(Math.random()*9+2);
//创建生成节点
var div = document .createElement("div");
//添加类名
div.className = 'ball'
//自定义属性保存值
div.speedX = Math .floor(Math.random()*9+2)
div.speedY = Math .floor(Math.random()*9+2)
//将div放置到body中
document.body.appendChild(div)
}
//获取元素
var box = document .getElementsByClassName( "ball" )
//获取文档可视区域的宽高
var maxX = document .documentElement.clientWidth - box[0].offsetWidth;
var maxY = document .documentElement.clientHeight - box[0].offsetHeight;
//自适应窗口
window.onresize = function (){
maxX = document .documentElement.clientWidth - box[0].offsetWidth;
maxY = document .documentElement.clientHeight - box[0].offsetHeight;
}
play()
function play(){
for(var i = 0 ;i<num;i++){
//获取
var ball = box [i];
var startTop = ball .offsetTop;
var startLift = ball .offsetLeft;
//startTop都为零;
var top = startTop + ball.speedY;
var left = startLift + ball.speedX;
//判断小球是否出左右边界
if(left <= 0 || left >= maxX){
//改变方向
ball.speedX = -ball.speedX;
ball.style.background=randomColor()
//判断
if(left <= 0){
left = 0;
}else if(left >= maxX){
left = maxX;
}
}
//判断小球是否出上下边界
if(top <= 0 || top >= maxY ){
// 改变方向;
ball.speedY = -ball.speedY;
ball.style.background=randomColor()
//判断
if( top <= 0 ){
top = 0;
}else if( top >= maxY ){
top = maxY;
}
}
ball.style.top = top + "px";
ball.style.left = left + "px";
}
//执行动画帧
requestAnimationFrame(play);
}
//颜色随机
function randomColor() {
var r = Math.floor(Math.random() * 256),
g = Math.floor(Math.random() * 256),
b = Math.floor(Math.random() * 256);
return "rgb(" + r + "," + g + "," + b + ")";
}
}
</ script >
</ body >
</ html >
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/javaScript1997/article/details/108385955