动态圣诞树代码用HTML写
时间: 2024-10-17 14:07:51 浏览: 54
动态的HTML圣诞树可以通过CSS动画和JavaScript交互来实现。下面是一个简单的例子,展示了一个基础的动态圣诞树,当用户点击树顶时星星会切换颜色:
```html
<!DOCTYPE html>
<html>
<head>
<style>
.tree {
position: relative;
}
.trunk {
width: 100px;
height: 300px;
background: #8B4513; /* 圣诞树色 */
position: absolute;
bottom: 0;
left: 50%;
transform: translateY(-50%) translateX(-50%);
}
.top-star {
position: absolute;
top: -70px;
left: 50%;
transform: translateX(-50%);
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid gold; /* 星星颜色 */
transition: all 0.5s ease-in-out;
}
.active-top-star {
animation: blink 1s infinite;
}
@keyframes blink {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 1; }
}
</style>
</head>
<body>
<div class="tree">
<div class="trunk trunk--active"></div>
<div class="top-star"></div>
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
var topStar = document.querySelector(".top-star");
topStar.classList.add("active-top-star");
// 点击树顶时切换星星颜色
document.querySelector(".trunk").addEventListener("click", function() {
if (topStar.classList.contains("active-top-star")) {
topStar.classList.remove("active-top-star");
} else {
topStar.classList.add("active-top-star");
}
});
});
</script>
</body>
</html>
```
在这个例子中,点击树干时,星星的颜色会切换,并且在动画状态下星星会闪烁。
阅读全文