Native JS achieve the effect of falling snow

But the pain hundred days long

<!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>

Guess you like

Origin blog.csdn.net/weixin_43553701/article/details/93388104