document.getElementsByTagName("body")[0].style.backgroundColor="#000"
//构造函数
function Ball( size, left1, top1, color, step, directionLeft, directionTop, timeSpace,opc){
this.dom = null
this.size = size
this.left1 = left1
this.top1 = top1
this.color = color
this.step = step
this.timeSpace = timeSpace
this.directionLeft = directionLeft
this.directionTop = directionTop
this.opc = opc
//创建球
this.createDom = function(){
this.dom = document.createElement("div")
this.dom.style.cssText = `
position: absolute;
left: ${this.left1}px;
top: ${this.top1}px;
width: ${this.size}px;
height: ${this.size}px;
border-radius: 50%;
background-color:${this.color};
opacity: ${this.opc};
z-index: -999999999;
`;
document.body.appendChild(this.dom)//吧效果加到body;里面
}
//球的动作
this.go = function () {
setInterval(() => {
this.left1 = this.left1 + this.directionLeft * this.step
this.top1 = this.top1 + this.directionTop * this.step
// 边界判断
let clientHeigth = document.documentElement.clientHeight || document.body.clientHeight
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
if (this.top1 + this.size > clientHeigth + scrollTop) {
this.top1 = clientHeigth + scrollTop - this.size
this.directionTop = -1
} else if (this.top1 < scrollTop) {
this.top1 = scrollTop
this.directionTop = 1
}
let clientWidth = document.documentElement.clientWidth || document.body.clientWidth
let scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
if (this.left1 + this.size > clientWidth + scrollLeft) {
// 右边界
this.left1 = clientWidth + scrollLeft - this.size
this.directionLeft = -1
} else if (this.left1 < scrollLeft) {
//左边界
this.left1 = scrollLeft
this.directionLeft = 1
}
this.dom.style.left = this.left1 + "px"
this.dom.style.top = this.top1 + "px"
}, this.timeSpace)
}
//调用
this.createDom()
this.go()
}
window.onload = function () {
var w = document.documentElement.clientWidth||document.body.clientWidth
var h =document.documentElement.clientHeight||document.body.clientHeight
for(var i=0;i<200;i++){
// 随机大小(10-150)
let size = parseInt(Math.random()*141)+10
// 随机位置;
let left1 = parseInt(Math.random()*w)
let top1 = parseInt(Math.random()*h)
// 随机颜色
let color = getColor()
// 随机步长(1-10)
let step = parseInt(Math.random()*5)+1
// 随机方向
let directionLeft = parseInt(Math.random()*2)==0?-1:1 //0和1
let directionTop = parseInt(Math.random()*2)==0?-1:1 //0和1
// 随机时间间隔(5-50)
let timeSpace = parseInt(Math.random()*46)+5
//透明度
let opc = (parseInt(Math.random()*6)+1)/10
new Ball( size, left1, top1, color, step, directionLeft, directionTop, timeSpace,opc)
}
}
function getColor(){//随机颜色
var str = "#"
for(var i=0;i<6;i++){
str += parseInt(Math.random()*16).toString(16)
}
return str
}