1. 程式人生 > >js實現雪花效果(超簡單)

js實現雪花效果(超簡單)

使用js實現雪花飄落效果,話不多說直接上程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>snow</title>
    <style>
        body,html{
            margin: 0;
            padding: 0;
            overflow: hidden;
            height: 100%;
            background
: black; } .snow{ background: white; position: absolute; width: 20px; height: 20px; border-radius: 50%; }
</style> </head> <body> <script> //獲取螢幕寬高 var windowWidth = window.screen.width; var
windowHeight = window.screen.height; //建立雪花 function createSnow(){ var left = 0; var top = 0; //定義一個初始化隨機數,使雪花在螢幕中 var left_random = Math.random() * windowWidth; var top_random = Math.random()* windowHeight; var div = document
.createElement('div'); div.className = 'snow'; div.style.transform = 'scale('+(Math.random())+')' document.body.appendChild(div); //雪花飄落 setInterval(function () { div.style.left = left_random + left +'px'; div.style.top = top_random + top +'px' left += 0.2; top += 0.2; //如果雪花跑到螢幕外面了,讓雪花重新返回螢幕頂部 if(left_random + left >= windowWidth){ left_random = Math.random(); left = 0; } if(top_random + top >= windowHeight){ top_random = Math.random(); top = 0; } },10) } for(var i = 0 ; i < 200 ; i++){ createSnow() }
</script> </body> </html>

實現邏輯其實很簡單,動態建立若干個div設定其樣式變成雪花,通過setInterval定時器控制雪花移動,當雪花跑到螢幕外面重新讓雪花的left或者top為0,使雪花重新回到最左或者最上面的位置,從而實現。

效果預覽: