HTML 部分:
标签中包含一个空的CSS 部分:
body 样式设置了背景为从顶部的 #000033(较深的蓝色)到底部的 #000000(黑色)的线性渐变,营造出夜空的效果。
.star-field 定义了绝对定位,占据整个屏幕的宽度和高度。
.star 为所有星星元素设置了绝对定位的基础样式。
三种不同形状的星星样式(.pentagram-star、.triangle-star、.hexagon-star)分别定义了各自的形状和颜色,并应用了相同的闪烁动画 blink。
@keyframes blink 定义了星星闪烁的关键帧,实现了从完全不透明到完全透明再到完全不透明的效果。
@keyframes delayBlink 这里暂时未被使用,可能是为了后续扩展或修改动画效果准备的。
JavaScript 部分:
createStar 函数用于创建单个星星元素。
首先创建一个 div 元素,并添加 star 类和对应形状的类(如 pentagram-star)。
然后通过随机数生成星星的位置(randomTop 和 randomLeft),并设置为元素的 top 和 left 样式。
接着生成一个随机的延迟时间(delay),并将其设置为星星元素的 animationDelay 样式,从而实现星星闪烁有先后顺序的效果。
最后将创建好的星星元素添加到 star-field 容器中。
在循环中,创建了 50 个随机形状的星星,并调用 createStar 函数进行创建和设置。
通过以上的 HTML、CSS 和 JavaScript 代码的配合,实现了随机分布、不同形状、有先后顺序闪烁的星星效果,模拟出了夜空繁星的景象。
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {
background: linear-gradient(to bottom, #000033 0%, #000000 100%);
}
.star-field {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.star {
position: absolute;
width: 20px;
height: 20px;
}
.pentagram-star {
clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
background-color: yellow;
animation: blink 2s infinite ease-in-out;
}
.triangle-star {
clip-path: polygon(50% 0%, 100% 100%, 0% 100%);
background-color: white;
animation: blink 2s infinite ease-in-out;
}
.hexagon-star {
clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);
background-color: lightblue;
animation: blink 2s infinite ease-in-out;
}
@keyframes blink {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes delayBlink {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
</style>
</head>
<body>
<div class="star-field"></div>
<script>
// 创建星星
function createStar(type) {
let star = document.createElement('div');
star.classList.add('star', type + '-star');
let randomTop = Math.random() * window.innerHeight;
let randomLeft = Math.random() * window.innerWidth;
star.style.top = randomTop + 'px';
star.style.left = randomLeft + 'px';
let delay = Math.random() * 5; // 随机延迟
star.style.animationDelay = delay +'s'; // 设置延迟
document.querySelector('.star-field').appendChild(star);
}
// 创建多种类型的星星
for (let i = 0; i < 50; i++) {
let randomType = Math.random() < 0.33? 'pentagram' : (Math.random() < 0.66? 'triangle' : 'hexagon');
createStar(randomType);
}
</script>
</body>
</html>