效果图:
说明:效果图片中的花瓣是图片,
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
overflow: hidden;
}
</style>
</head>
<body>
<script>
// 从a到b的随机数
function ranDom(a, b) {
var r = parseInt(Math.random() * (b - a + 1)) + a;
return r;
}
// 构造函数
function Girl(top, right) {
this.top = top;
this.right = right;
// 创建的方法
this.init = function () {
// 创建节点, 节点的样式, 节点拼接
this.dom = document.createElement('div');
this.dom.style.cssText = `width: 30px; height: 30px; position: absolute; background: url(img/hb${ranDom(1, 3)}.png) no-repeat; background-position: 0px -2px;`;
this.dom.style.top = this.top + 'px';
this.dom.style.right = this.right + 'px';
document.body.appendChild(this.dom);
}
// 移动的方法
this.move = function () {
// 此处的this为新创建的Girl对象, 把this保存一份(self), 在进入定时器内部再使用
// console.log(this);
var self = this;
// 声明变量: 位置, 图片编码(0-7)
var top = 0;
var index = 0;
// 定时器, top实时改变, index++
this.timer = setInterval(function () {
top += 5;
index++;
// 验收index
if (index > 7) index = 0;
// 验收top
if (top >= 1000) self.byebye();
// 位置改变
// console.log(this); // window
// console.log(this.dom); // undefined
// console.log(self); // Girl对象
// console.log(self.dom); // div
self.dom.style.top = top + 'px';
// 图片切换
// self.dom.style.backgroundPosition = -79 * index + 'px -216px';
}, 50);
}
// 消失的方法
this.byebye = function () {
// 清除定时器
clearInterval(this.timer);
// 移除节点
this.dom.remove();
}
this.init();
this.move();
}
setInterval(() => {
new Girl(0, ranDom(100, 900));
new Girl(0, ranDom(100, 900));
new Girl(0, ranDom(100, 900));
new Girl(0, ranDom(100, 900));
}, 1000)
setInterval(() => {
new Girl(0, ranDom(100, 900));
new Girl(0, ranDom(100, 900));
}, 1500)
setInterval(() => {
new Girl(0, ranDom(500, 1200));
new Girl(0, ranDom(500, 1200));
}, 2000)
</script>
</body>
</html>