代码如下:
<!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){
for(var i=0;i<num;i++){
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)
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;
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://tech.qufami.com/read-13095.html