html动态背景特效星空
时间: 2023-09-01 21:07:48 浏览: 94
可以使用CSS3动画和JavaScript来实现一个星空的动态背景特效。
首先,在HTML中创建一个div用来作为背景:
```html
<div id="stars"></div>
```
然后,在CSS中设置该div的样式,并使用CSS3动画让星星随机移动:
```css
#stars {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
z-index: -1;
}
.star {
position: absolute;
width: 2px;
height: 2px;
background-color: #fff;
border-radius: 50%;
animation: twinkle linear infinite;
}
@keyframes twinkle {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
```
接着,在JavaScript中使用循环创建一定数量的星星,并随机设置它们的位置和动画延迟时间:
```javascript
const numStars = 100; // 星星数量
const stars = document.getElementById("stars");
// 循环创建星星
for (let i = 0; i < numStars; i++) {
const star = document.createElement("div");
star.className = "star";
stars.appendChild(star);
// 随机设置星星的位置和动画延迟时间
const xy = getRandomPosition();
star.style.top = xy[0] + "px";
star.style.left = xy[1] + "px";
star.style.animationDelay = Math.random() * 10 + "s";
}
// 随机生成位置
function getRandomPosition() {
const y = window.innerHeight;
const x = window.innerWidth;
const randomY = Math.floor(Math.random() * y);
const randomX = Math.floor(Math.random() * x);
return [randomY, randomX];
}
```
最后,将CSS和JavaScript代码保存到文件中,并在HTML中引入它们:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>星空背景特效</title>
<style>
/* CSS代码 */
</style>
</head>
<body>
<div id="stars"></div>
<script>
// JavaScript代码
</script>
</body>
</html>
```
这样就可以实现一个简单的星空动态背景特效了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)