js使用面向对象实现星星闪烁。
首先是js代码:
在这里插入代码片
//创建萤火虫节点:code
//萤火虫随机位置:clientLeft or height
//萤火虫的显示:show
//萤火虫飞:fly,调用运动move.js
function FirmWorm(){
this.code=document.createElement("img"); //创建节点
this.code.src="1.jpg"; //节点图片
// document.body.appendChild(this.code)
}
FirmWorm.prototype.Position=function(){
var x=document.documentElement.clientWidth; //var x是每个节点在可视区的左侧距离
var y=document.documentElement.clientHeight;//var y是每个节点在可视区的顶部距离
this.posX=Math.floor(Math.random()*(x-20)); //随机左侧距离,减去自身的宽度
this.posY=Math.floor(Math.random()*(y-20)); //随机顶部距离,减去自身的高度
}
FirmWorm.prototype.show=function(){ //需要调用随机的位置显示
this.Position();
this.code.style.left=this.posX+"px"; //左侧距离
this.code.style.top=this.posY+"px"; //顶部距离
// 将code放到body里面
document.body.appendChild(this.code) //将每个萤火虫放到body里面
}
FirmWorm.prototype.Fly=function(){
this.Position();
move(this.code,{"left":this.posX,"top":this.posY},()=>{ //引入move函数(对象,移动属性和值,前两步执行之后再执行第三个参数)
this.Fly();
})
}
for(var i=0;i<100;i++){
var firm=new FirmWorm();
firm.show();
firm.Fly();}
``
以下是引入的move.js代码:
function move(domobj, json, fn) {
clearInterval(domobj.timer);
domobj.timer = setInterval(function () {
let flag = true;
for (let attr in json) {
if (attr == "opacity") {
var iCur = getStyle(domobj, attr) * 100;
} else {
var iCur = parseInt(getStyle(domobj, attr));
}
let iTarget = parseInt(json[attr]);
let iSpeed = (iTarget - iCur) / 10;
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
if (attr == "opacity") {
domobj.style.opacity = (iCur + iSpeed) / 100;
domobj.style.filter = "alpha(opacity=" + (iCur + iSpeed) + ")";
} else {
domobj.style[attr] = iCur + iSpeed + "px";
}
if (iSpeed != 0) {
flag = false;
}
}
if (flag) {
clearInterval(domobj.timer);
if (fn) {
fn();
}
}
}, 20);
}
function getStyle(domobj, attr) {
if (window.getComputedStyle) {
return getComputedStyle(domobj, null)[attr];
}
return domobj.currentStyle[attr];
}