<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>滿天星</title> <style> *{ margin: 0; padding: 0; } html,body { width: 100%; height: 100%; position: relative; } .star-animation { position: relative; top: 0; left: 0; width: 100%; height: 100%; background-color: black; overflow: hidden; } /*動畫設計*/ @-webkit-keyframes identifier { 25% { transform: scale(1.5); } 50% { transform: scale(2); } 75% { transform: scale(1.5); } 100% { transform: scale(1); } } @-o-keyframes identifier { 25% { transform: scale(1.5); } 50% { transform: scale(2); } 75% { transform: scale(1.5); } 100% { transform: scale(1); } } @-moz-keyframes identifier { 25% { transform: scale(1.5); } 50% { transform: scale(2); } 75% { transform: scale(1.5); } 100% { transform: scale(1); } } @keyframes identifier { 25% { transform: scale(1.5); } 50% { transform: scale(2); } 75% { transform: scale(1.5); } 100% { transform: scale(1); } } </style> </head> <body> <div></div> <div class="star-animation"></div> </body> <script> // 自調用函數,在加載該文件時就開始工做 (function(container) { // window.innerWidth 控制星星的密度 for (var i = 0; i < window.innerWidth/5; i++) { container.append(starFactory()); } })(document.getElementsByClassName("star-animation")[0]); // 建立星星的一個工廠函數 function starFactory() { let star = document.createElement("div"); let width = Math.ceil(Math.random()*5); star.style.position = "absolute"; star.style.width = width + 'px'; star.style.height = width + 'px'; star.style.backgroundColor = '#909090'; star.style.top = Math.ceil(Math.random()*window.innerHeight) + 'px'; star.style.left = Math.ceil(Math.random()*window.innerWidth) + 'px'; star.style.boxShadow = "#545454 0 0 "+1+"px "+1+"px"; star.style.borderRadius = width + 'px'; // 當星星直徑小於3時,有一個放大縮小的動畫 if (width < 3) { star.style.boxShadow = "#545454 0 0 "+width/2+"px "+width/2+"px"; star.style.animation = "identifier 2000ms infinite 500ms"; } return star; } </script> </html>
效果:html