每次刷新星星的位置都是随机的,可以根据自己需求调整星星的数量和位置,具体代码如下,直接复制就可运行
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Random Starry Sky</title> 5 <style> 6 body { 7 margin: 0; 8 overflow: hidden; 9 background-color: #000; 10 } 11 .stars { 12 width: 100%; 13 height: 100%; 14 position: fixed; 15 top: -10%; 16 left: 0; 17 z-index: -1; 18 } 19 .star { 20 position: absolute; 21 background-color: white; 22 border-radius: 50%; 23 } 24 </style> 25 </head> 26 <body> 27 <div class="stars"> 28 <div>你是谁</div> 29 </div> 30 31 <script> 32 function generateStars(count) { 33 const stars = []; 34 const centerX = window.innerWidth / 2; 35 const centerY = window.innerHeight / 2; 36 const maxDistance = Math.min(centerX, centerY) * 2; 37 for (let i = 0; i < count; i++) { 38 const angle = Math.random() * 2 * Math.PI; 39 const distance = Math.random() * maxDistance; 40 const x = centerX + Math.cos(angle) * distance; 41 const y = centerY + Math.sin(angle) * distance; 42 43 const star = document.createElement('div'); 44 star.className = 'star'; 45 star.style.top = `${y}px`; 46 star.style.left = `${x}px`; 47 star.style.width = `${Math.random() * 2 + 1}px`; 48 star.style.height = star.style.width; 49 star.style.opacity = Math.random(); 50 stars.push(star); 51 } 52 return stars; 53 } 54 const starContainer = document.querySelector('.stars'); 55 const stars = generateStars(700); 56 stars.forEach(star => starContainer.appendChild(star)); 57 </script> 58 </body> 59 </html>
标签:style,const,星空,random,js,css,stars,star,Math From: https://www.cnblogs.com/ximenchuifa/p/17839030.html