萤火虫
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
html {
height: 100%;
}
body {
padding: 0;
margin: 0;
height: 100%;
background: url(bg.jpg) no-repeat;
background-size: cover;
}
img {
width: 20px;
position: absolute;
}
</style>
</head>
<body>
<script>
无论是在构造函数里还是在原型方法里,如果一个变量只在该方法体内部使用,用var,也称为私有属性
但是一个变量不仅在构造函数里能访问,并且在原型方法里也能被访问到,就放到this上,变成实例属性
//萤火虫要飞
//1.先创建萤火虫类
function Fireworm() {
//知道是萤火虫
this.node = document.createElement("img");
this.node.src = "1.jpg";
}
//萤火虫得有随机位置
Fireworm.prototype.getRandPos = function () {
var cw = document.documentElement.clientWidth; //可是区域的宽
var ch = document.documentElement.clientHeight;
var maxW = cw - 20;
var maxH = ch - 20;
this.x = Math.floor(Math.random() * maxW);
this.y = Math.floor(Math.random() * maxH);
}
//萤火虫要显示
Fireworm.prototype.show = function () {
this.getRandPos();
this.node.style.left = this.x + "px";
this.node.style.top = this.y + "px";
document.body.appendChild(this.node);
}
//萤火虫要飞
Fireworm.prototype.fly = function () {
this.getRandPos();
startMove(this.node, {
left: this.x,
top: this.y
}, () => {
console.log(this);
this.fly();
});
}
</script>
<script>
运动封装函数
function startMove(domobj, json, fn) {
clearInterval(domobj.timer);
domobj.timer = setInterval(function () {
var flag = true; //假设所有的属性都达到了目标值
for (var attr in json) {
var iTarget = json[attr]; //取到目标值
if (attr == "opacity") { //透明度的处理
var iCur = parseInt(getStyle(domobj, "opacity") * 100);
} else {
var iCur = parseInt(getStyle(domobj, attr)); //取到当前值
}
var iSpeed = (iTarget - iCur) / 8;
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 (iTarget != iCur) { //只要有没达到的 flag为false
flag = false;
}
}
if (flag) { //只有在flag为true时才清定时器
clearInterval(domobj.timer);
if (fn) {
fn();
}
}
},50)
}
function getStyle(domobj, attr) {
if (window.getComputedStyle) {
return getComputedStyle(domobj, null)[attr];
}
return domobj.currentStyle[attr];
}
</script>
</body>
</html>
下方是萤火虫图片