<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, ini
ul, ol { list-style: none;}tial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
a {border: none;text-decoration: none;color: inherit;}
* {margin: 0;padding: 0;}
.clearfix:after{content: '';display: block;clear: both;}
.fl,.fl_child > *{float: left;}
.fr,.fr_child > *{float: right;}
body{
background-color: black;
}
p{
position: absolute;
left: 0;
top: 0;
width: 50px;
height: 50px;
background-color: #990FDE;
border-radius: 50%;
}
</style>
<title>跳动的小球</title>
</head>
<body>
<script>
/* 动态获取 */
var aP = document.getElementsByTagName('p');
/* 创建小球 */
var length = 30;
for( var i=0; i<length; i++ ){
document.body.append(document.createElement('p'));
}
/* 初始化步长 */
var xStep = [];
var yStep = [];
for( var i=0; i<length; i++ ){
xStep[i]= 5+i;
yStep[i]= 5+i;
}
console.log(xStep+"============"+yStep);
/* 定时器 */
setInterval(function (){
/* 小球反弹条件 */
var Width = document.documentElement.clientWidth -aP[0].clientWidth;
var Height = document.documentElement.clientHeight -aP[0].clientHeight;
/* */
for( var i=0; i<length; i++ ){
var left = aP[i].offsetLeft + xStep[i];
var Top = aP[i].offsetTop + yStep[i];
/* 碰壁反弹 */
if(left>Width||left<0){
left = Math.max(left,0);
left = Math.min(left,Width);
xStep[i] = -xStep[i];
change(i);
}
if(Top>Height||Top<0) {
Top = Math.max(Top, 0);
Top = Math.min(Top, Height);
yStep[i] = -yStep[i];
change(i);
}
aP[i].style.left = left + 'px';
aP[i].style.top = Top + 'px';
}
},20)
/* 小球随机改变颜色 */
function change(n) {
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
aP[n].style.backgroundColor = "rgb("+r+","+g+","+b+")";
}
</script>
</body>
</html>