HTML和CSS代码实现带动态繁星背景特效
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>动态繁星背景</title>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
}
.stars {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
z-index: 0;
}
.stars-container {
position: absolute;
width: 100%;
height: 100%;
}
.star {
position: absolute;
width: 2px;
height: 2px;
background: white;
opacity: 0.3;
border-radius: 50%;
box-shadow:
inset 0 0 5px #fff,
0 0 5px #fff;
animation: twinkle 1s infinite alternate;
}
@keyframes twinkle {
from {
opacity: 0.3;
transform: scale(0.5);
}
to {
opacity: 1;
transform: scale(1);
}
}
</style>
</head>
<body>
<div class="stars">
<div class="stars-container"></div>
</div>
<script>
const container = document.querySelector('.stars-container');
const numStars = 1000; // 可以根据需要调整星星数量
for (let i = 0; i < numStars; i++) {
const star = document.createElement('div');
star.classList.add('star');
const size = Math.random() * 2;
const x = Math.random() * window.innerWidth;
const y = Math.random() * window.innerHeight;
star.style.width = `${size}px`;
star.style.height = `${size}px`;
star.style.left = `${x}px`;
star.style.top = `${y}px`;
container.appendChild(star);
}
</script>
</body>
</html>
这段代码创建了一个包含1000个随机大小和位置的星星的动态背景。每个星星都是通过JavaScript动态生成并附加CSS样式的。星星的动画效果是通过CSS的@keyframes
实现的,它会随机大小和位置生成星星,并且通过animation
属性实现闪烁效果。
评论已关闭