JS*千字墙效果
最近在学习js的继承,类过程中,突发奇想,信手拈来,本着以class类,prototype原型,构造函数及对象的思想为中心,学习中封装了一个随机动态地中华千字文的效果;
效果如下:
htmlCode:
jsCode
/**
function Box(parent,options) {
options = options||{}
this.backgroundColor = options.backgroundColor || ‘red’;
this.borderRadius = options.borderRadius || ‘100%’;
this.width = options.width || 100;
this.height = options.height || 100;
this.x = options.x || 0;
this.y = options.y || 0;
this.div1 = document.createElement(‘div’);
this.div1.innerHTML = getRandomText();
parent.appendChild(this.div1);
this.parent = parent;
this.init();
}
Box.prototype.init = function(){
var div = this.div1;
div.style.backgroundColor = this.backgroundColor;
div.style.borderRadius = this.borderRadius;
div.style.width = this.width + ‘px’;
div.style.height = this.height + ‘px’;
div.style.left = this.x + “px”;
div.style.top = this.y + “px”;
div.style.position = ‘absolute’;
}
Box.prototype.random = function(){
var x = Tools.getRandom(0,this.parent.offsetWidth/this.width - 2)*this.width;
var y = Tools.getRandom(0,this.parent.offsetHeight/this.height - 2)*this.height;
this.div1.style.left = x + ‘px’;
this.div1.style.top = y + ‘px’
}
//随机生成文字
function getRandomText(){
eval( “var word=” + ‘"\u’ + (Math.round(Math.random() * 20901) + 19968).toString(16)+’"’)
return word
}
/**
var container = document.getElementById(‘container’);
var arr = []
for(var i = 0;i<100;i++){
var r = Tools.getRandom(0,255);
var g = Tools.getRandom(0,255);
var b = Tools.getRandom(0,255);
var box = new Box(container,{
backgroundColor:‘rgb(’+r+’,’+g+’,’+b+’)’,
borderRadius:‘100%’,
display: ‘flex’,
justifyContent: ‘center’,
alignItems: ‘center’,
})
arr.push(box);
}
setInterval(randomBox,2000);
randomBox();
function randomBox(){
for(var i=0;i<arr.length;i++){
var box = arr[i];
box.random()
}
}
/**
var Tools = {
getRandom:function(min,max){
return Math.floor(Math.random()*(max-min+1))+min;
}
}
cssCode
html,body{
padding:0;
margin:0;
width:100%;
height: 100%;
}
#container{
width: 100%;
height: 100%;
background-color:rgba(0,0,0,0.5);
position: relative;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
font-size: 60px;
}