效果圖
代碼如下:
css代碼
*{
margin: 0;
padding: 0;
}
/* 設(shè)置html和body標(biāo)簽的寬高和瀏覽器可視區(qū)域一樣*/
html, body{
width: 100%;
height: 100%;
}
/* 設(shè)置小球移動(dòng)范圍的相關(guān)樣式*/
#wrap{
width: 100%;
height: 100%;
background-color: black;
position: relative;
overflow: hidden;
}
.boll{
position: absolute;
border-radius: 50%;
}
js代碼
window.onload = function () {
//工具函數(shù):產(chǎn)生指定范圍內(nèi)的隨機(jī)數(shù)
function randFn(min, max) {
return parseInt(Math.random() * (max - min) + min);
}
//獲取容器節(jié)點(diǎn)(減少document操作次數(shù),減少損耗)
var wrap = document.querySelector('#wrap');
// 創(chuàng)建小球?qū)ο蟮臉?gòu)造函數(shù)
function Boll(wh) {
// 隨機(jī)產(chǎn)生小球的寬高
var wh = randFn(20, 50);
// 設(shè)置寬高屬性和屬性值
this.width = wh;
this.height = wh;
// 設(shè)置小球誕生點(diǎn)的坐標(biāo)屬性
this.top = randFn(0, document.body.offsetHeight - wh)? + 'px';
this.left = randFn(0, document.body.offsetWidth - wh) + 'px';
//設(shè)置小球隨機(jī)背景顏色 rgba
//rgba(255,255,255,0.5)
this.color = 'rgba(' + randFn(0, 255) + ',' + randFn(0,255) + ',' + randFn(0, 255) + ',' + Math.random() + ')';
// 設(shè)置小球隨機(jī)移動(dòng)速度的屬性
this.speedX = randFn(-10, 10);
this.speedY = randFn(-10, 10);
// 設(shè)置保存小球標(biāo)簽的屬性
this.div = document.createElement('div');
}
// 原型方法: 繪制小球(配置div標(biāo)簽的相關(guān)css樣式,然后把標(biāo)簽接進(jìn)文檔流)
Boll.prototype.draw = function () {
this.div.className = 'boll';
// 配置小球?qū)捀?/p>
this.div.style.width = this.width + 'px';
this.div.style.height = this.height + 'px';
//小球誕生點(diǎn)
this.div.style.top = this.top;
this.div.style.left = this.left;
//小球背景顏色
this.div.style.backgroundColor = this.color;
// 把配置好的節(jié)點(diǎn)拼接進(jìn)文檔流
wrap.appendChild(this.div);
}
// 原型方法:讓小球移動(dòng),且碰壁反彈
Boll.prototype.run = function () {
//因?yàn)樵诙〞r(shí)器中使用的this指針是指向window對(duì)象的,要在定時(shí)器中獲取當(dāng)前操作的小球?qū)ο?就必須在定時(shí)器外部用變量把當(dāng)前操作小球?qū)ο蟊4嫦聛?lái),在定時(shí)器內(nèi)部通過(guò)該變量獲取小球?qū)ο?/p>
var self = this;
setInterval(function () {
//判斷小球是否撞墻
var tag = self.div
if (tag.offsetLeft + tag.offsetWidth >= wrap.offsetWidth || tag.offsetLeft < 0) {
self.speedX *= -1;
}
if (tag.offsetTop + tag.offsetHeight >= wrap.offsetHeight || tag.offsetTop < 0) {
self.speedY *= -1;
}
tag.style.left = tag.offsetLeft + self.speedX + 'px';
tag.style.top = tag.offsetTop + self.speedY + 'px';
},30)
}
for (var i = 0; i < 100; i++) {
//創(chuàng)建小球?qū)ο?/p>
var boll = new Boll();
//調(diào)用對(duì)象繪制方法,把小球繪制進(jìn)文檔
boll.draw();
//調(diào)用小球移動(dòng)
boll.run();
}
}
html
//小球移動(dòng)范圍
<div id = 'wrap'>
</div>