浪漫星空html代码
时间: 2023-11-26 22:47:40 浏览: 49
以下是一个简单的浪漫星空HTML代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>浪漫星空</title>
<style>
body {
background-color: black;
}
.stars {
position: absolute;
width: 1px;
height: 1px;
background-color: white;
}
</style>
</head>
<body>
<script>
// 创建星星
function createStar() {
// 创建一个div元素
var star = document.createElement("div");
// 设置星星的class为stars
star.setAttribute("class", "stars");
// 设置星星的位置
star.style.left = Math.random() * window.innerWidth + "px";
star.style.top = Math.random() * window.innerHeight + "px";
// 将星星添加到body中
document.body.appendChild(star);
}
// 创建多个星星
function createStars() {
// 创建100个星星
for (var i = 0; i < 100; i++) {
createStar();
}
}
// 闪烁效果
function twinkle() {
// 获取所有的星星
var stars = document.getElementsByClassName("stars");
// 遍历所有的星星
for (var i = 0; i < stars.length; i++) {
// 随机设置星星的透明度
stars[i].style.opacity = Math.random();
}
}
// 定时器,每隔0.5秒执行一次twinkle函数
setInterval(twinkle, 500);
// 创建多个星星
createStars();
</script>
</body>
</html>
```