<!DOCTYPE html>
<html>
<head>
	<title>动态星轨</title>
	<style>
		body {
			background-color: black;
		}
		.star {
			position: absolute;
			width: 2px;
			height: 2px;
			border-radius: 50%;
			background-color: white;
			animation: twinkling 1s infinite;
		}
		@keyframes twinkling {
			0% {opacity: 1;}
			50% {opacity: 0.5;}
			100% {opacity: 1;}
		}
	</style>
</head>
<body>
	<script>
		// 创建100个星星
		for (var i = 0; i < 100; i++) {
			var star = document.createElement("div");
			star.className = "star";
			star.style.left = Math.random() * window.innerWidth + "px";
			star.style.top = Math.random() * window.innerHeight + "px";
			document.body.appendChild(star);
		}
<pre><code>	// 每隔50毫秒改变星星的位置
	setInterval(function() {
		var stars = document.getElementsByClassName(&quot;star&quot;);
		for (var i = 0; i &lt; stars.length; i++) {
			var star = stars[i];
			var x = parseFloat(star.style.left);
			var y = parseFloat(star.style.top);
			x += Math.random() * 4 - 2;
			y += Math.random() * 4 - 2;
			if (x &lt; 0) x = window.innerWidth;
			if (x &gt; window.innerWidth) x = 0;
			if (y &lt; 0) y = window.innerHeight;
			if (y &gt; window.innerHeight) y = 0;
			star.style.left = x + &quot;px&quot;;
			star.style.top = y + &quot;px&quot;;
		}
	}, 50);
&lt;/script&gt;
</code></pre>
</body>
</html

原文地址: https://www.cveoy.top/t/topic/fE3Z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录