<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #box { width: 800px; height: 600px; background-color: lightgrey; position: relative; } </style> </head> <body> <div id='box'></div> <script src='tools.js'></script> <script src='box.js'></script> <script src='main.js'></script> <script> window.onload = function() { main(); } </script> </body> </html>
function getRandom(min,max) { return Math.floor(Math.random()*(max - min + 1)) + min; }
function Box(parent,options) { options = options || {}; this.width = options.width || 20; this.height = options.height || 20; this.color = options.color || 'pink'; this.x = options.x || 0; this.y = options.y || 0; this.parent = parent; this.init(); } var position = 'absolute'; Box.prototype.init = function() { var box = document.createElement('div'); box.style.width = this.width + 'px'; box.style.height = this.height + 'px'; box.style.backgroundColor = this.color; box.style.position = position; box.style.left = this.x + 'px'; box.style.top = this.y + 'px'; this.parent.appendChild(box); } Box.prototype.random = function() { var x = getRandom(0,this.parent.offsetWidth/this.width - 1) * this.width; var y = getRandom(0,this.parent.offsetHeight/this.height - 1) * this.height; return { x: x, y: y } } // 测试代码 // var parent = document.getElementById('box'); // var box = new Box(parent);
function main() { var parent = document.getElementById('box'); var arr = []; for(var i = 0; i < 10; i++) { var r = getRandom(0,255); var g = getRandom(0,255); var b = getRandom(0,255); var box = new Box(parent,{ color: 'rgb('+ r +','+ g +','+ b +')' }) arr.push(box); } randomIndex(); setInterval(randomIndex,500); function randomIndex() { for(var i = 0; i < arr.length; i++) { var x = arr[i].random().x; var y = arr[i].random().y; parent.children[i].style.left = x + 'px'; parent.children[i].style.top = y + 'px'; } } }
运行结果: