效果圖
代碼如下:
css代碼
*{
margin: 0;
padding: 0;
}
/* 設置html和body標簽的寬高和瀏覽器可視區域一樣*/
html, body{
width: 100%;
height: 100%;
}
/* 設置小球移動范圍的相關樣式*/
#wrap{
width: 100%;
height: 100%;
background-color: black;
position: relative;
overflow: hidden;
}
.boll{
position: absolute;
border-radius: 50%;
}
js代碼
window.onload = function () {
//工具函數:產生指定范圍內的隨機數
function randFn(min, max) {
return parseInt(Math.random() * (max - min) + min);
}
//獲取容器節點(減少document操作次數,減少損耗)
var wrap = document.querySelector('#wrap');
// 創建小球對象的構造函數
function Boll(wh) {
// 隨機產生小球的寬高
var wh = randFn(20, 50);
// 設置寬高屬性和屬性值
this.width = wh;
this.height = wh;
// 設置小球誕生點的坐標屬性
this.top = randFn(0, document.body.offsetHeight - wh)? + 'px';
this.left = randFn(0, document.body.offsetWidth - wh) + 'px';
//設置小球隨機背景顏色 rgba
//rgba(255,255,255,0.5)
this.color = 'rgba(' + randFn(0, 255) + ',' + randFn(0,255) + ',' + randFn(0, 255) + ',' + Math.random() + ')';
// 設置小球隨機移動速度的屬性
this.speedX = randFn(-10, 10);
this.speedY = randFn(-10, 10);
// 設置保存小球標簽的屬性
this.div = document.createElement('div');
}
// 原型方法: 繪制小球(配置div標簽的相關css樣式,然后把標簽接進文檔流)
Boll.prototype.draw = function () {
this.div.className = 'boll';
// 配置小球寬高
this.div.style.width = this.width + 'px';
this.div.style.height = this.height + 'px';
//小球誕生點
this.div.style.top = this.top;
this.div.style.left = this.left;
//小球背景顏色
this.div.style.backgroundColor = this.color;
// 把配置好的節點拼接進文檔流
wrap.appendChild(this.div);
}
// 原型方法:讓小球移動,且碰壁反彈
Boll.prototype.run = function () {
//因為在定時器中使用的this指針是指向window對象的,要在定時器中獲取當前操作的小球對象,就必須在定時器外部用變量把當前操作小球對象保存下來,在定時器內部通過該變量獲取小球對象
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++) {
//創建小球對象
var boll = new Boll();
//調用對象繪制方法,把小球繪制進文檔
boll.draw();
//調用小球移動
boll.run();
}
}
html
//小球移動范圍
<div id = 'wrap'>
</div>