雪花飘落

原生JS实现雪花飘落效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}

body {
width: 100%;
height: 100%;
background-color: #000;
overflow: hidden;
}
</style>
</head>

<body>
<div id="flame"></div>
<script>
// 创建一个对象
function Obj() {};

// 给这个对象添加一个具有参数的原型方法
Obj.prototype.draw = function(o) {
// 雪花每次下落的数值
var speed = 0;
//设置雪花随机的开始x值的大小
var startPosLeft = Math.ceil(Math.random() * document.documentElement.clientWidth);
// 设置透明度
o.style.opacity = (Math.ceil(Math.random() * 3) + 7) / 10;
o.style.left = startPosLeft + 'px';
o.style.color = "#fff";
o.style.fontSize = 12 + Math.ceil(Math.random() * 14) + 'px';
setInterval(function() {
if (speed < document.documentElement.clientHeight) {
o.style.top = speed + 'px';
o.style.left = startPosLeft + Math.ceil(Math.random() * 8) + 'px';
speed += 10;
} else {
o.style.display = 'none';
}
}, 400);
}

var alame = document.getElementById('flame');


// 定时器每隔一秒创建一个雪花
setInterval(function() {
// 创建一个div
var odiv = document.createElement('div');
// 给div 里面添加一个雪花
odiv.innerHTML = '✽';
// div 设置绝对定位,脱离标准流
odiv.style.position = 'absolute';
// 将创建出来的div 追加到原由的div里面
flame.appendChild(odiv);
// 创建一个函数
var obj = new Obj();
// 执行方法
obj.draw(odiv);
}, 800);
</script>
</body>

</html>

封装成js文件就可以当一个插件使用

文章目录
  1. 1. 原生JS实现雪花飘落效果
|