写一段动态星轨的HTML代码
<!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("star");
for (var i = 0; i < 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 < 0) x = window.innerWidth;
if (x > window.innerWidth) x = 0;
if (y < 0) y = window.innerHeight;
if (y > window.innerHeight) y = 0;
star.style.left = x + "px";
star.style.top = y + "px";
}
}, 50);
</script>
</code></pre>
</body>
</html
原文地址: https://www.cveoy.top/t/topic/fE3Z 著作权归作者所有。请勿转载和采集!