js随机生成闪烁div效果
<html>
<head>
<title> </title>
<!-- 设置CSS样式 -->
<style>
#contentBox{
width: 600px;
height: 800px;
background-color: #000000;
position: relative; /*设置相对定位*/
}
</style>
<script>
//创建一个工具类对象 静态的对象 也就是工具类的创建方式
var Tools = {
getRandom:function(min,max){
return Math.floor(Math.random()*(max-min+1))+min;
}
}
//1创建一个实例对象的 需要将创建的box加入哪个容器中,2 这个box有哪些属性
function Box(parent,options){
var options = options || {};
//这个盒子有哪些属性了?
this.backgroundColor = options.backgroundColor ||'red';
this.width = options.width || 8;
this.height = options.height || 8;
this.x = options.x || 0;
this.y = options.y || 0;
//然后生存盒子在把这些熟悉绑定上去
this.div = document.createElement('div');
//把生成的div绑定到父容器中
parent.appendChild(this.div);
this.parent = parent; //这样后续也可以使用到 parent这个属相
//设定这个div的css样式
this.init(); //注意这个this代表着 创建的div对象 也就是 var box1 = new Box()对象
}
//初始化盒子的样式
Box.prototype.init = function(){
this.div.style.backgroundColor = this.backgroundColor;
this.div.style.width = this.width +'px';
this.div.style.height = this.height +'px';
this.div.style.left = this.x + 'px';
this.div.style.top = this.y + 'px';
this.div.style.position = 'absolute';
}
//随机生成盒子的位置
Box.prototype.random = function(){
var x = Tools.getRandom(0,this.parent.offsetWidth/this.width-1)*this.width;
var y = Tools.getRandom(0,this.parent.offsetHeight/this.height-1)*this.height;
this.div.style.left = x + 'px';
this.div.style.top = y + 'px';
}
</script>
</head>
<body>
<div id="contentBox">
</div>
</body>
<script>
var parent = document.getElementById('contentBox');
var boxs = [];
for(var i = 0; i < 30 ; i++){
var r =Tools.getRandom(0,255);
var g =Tools.getRandom(0,255);
var b =Tools.getRandom(0,255);
var box1 = new Box(parent,{
backgroundColor: 'rgb('+r+','+g+','+b+')'
});
boxs.push(box1);
}
//创建定时器
setInterval(getRandomBox,1000);
getRandomBox();
function getRandomBox(){
for(var i = 0; i<boxs.length; i++){
var box = boxs[i];
box.random();
}
}
</script>
</html>
1.设置CSS样式:

2.HTML内容:

3:JS脚本


4:调用JS脚本

5:运行结果

坚持

浙公网安备 33010602011771号