以下是一个简单的生日蛋糕示例:
<!DOCTYPE html>
<html>
<head>
<title>Birthday Cake with JavaScript</title>
<style type="text/css">
#cake {
width: 500px;
height: 500px;
background-color: pink;
border-radius: 50% 50% 0 0;
position: relative;
overflow: hidden;
margin: auto;
}
#cake:before {
content: "";
width: 50px;
height: 50px;
border-radius: 50%;
background-color: white;
position: absolute;
right: -25px;
top: -25px;
}
#cake:after {
content: "";
width: 20px;
height: 20px;
border-radius: 50%;
background-color: yellow;
position: absolute;
left: -10px;
top: -10px;
}
#cake .candle {
width: 20px;
height: 50px;
background-color: white;
position: absolute;
top: -50px;
left: 50%;
transform: translate(-50%, 0);
border-radius: 5px 5px 0 0;
}
#cake .flame {
width: 10px;
height: 30px;
background-color: yellow;
position: absolute;
bottom: 0;
left: 50%;
transform: translate(-50%, 0);
border-radius: 50%;
animation: flicker 0.5s ease-out infinite alternate;
}
@keyframes flicker {
0% {
opacity: 1;
}
100% {
opacity: 0.5;
}
}
</style>
</head>
<body>
<div id="cake">
<div class="candle"></div>
<div class="flame"></div>
</div>
<script type="text/javascript">
// 延迟2秒钟开始动画
setTimeout(function () {
// 添加火花
for (var i = 0; i < 30; i++) {
var x = Math.random() * 500;
var y = Math.random() * 500;
var spark = document.createElement("div");
spark.className = "spark";
spark.style.left = x + "px";
spark.style.top = y + "px";
document.body.appendChild(spark);
setTimeout(function () {
spark.remove();
}, 1000);
}
// 移除蜡烛
document.querySelector(".candle").remove();
}, 2000);
</script>
</body>
</html>
这个示例使用CSS创建了一个粉色的圆形部分,表示蛋糕。它还使用伪元素和绝对定位添加了白色后和黄色火花。然后,使用JavaScript在页面加载2秒钟后,使用循环添加其他30个单独的黄色火花。最后,蜡烛将被删除。