js写一个圣诞树怎么做
时间: 2023-04-08 17:01:03 浏览: 96
你可以使用 HTML 和 CSS 来创建一个圣诞树,然后使用 JavaScript 来添加动态效果。以下是一个简单的示例代码:
HTML:
```html
<div id="tree"></div>
```
CSS:
```css
#tree {
width: 100px;
height: 150px;
background-color: green;
position: relative;
}
#tree:before {
content: "";
position: absolute;
top: 0;
left: 50%;
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 75px solid green;
}
#tree:after {
content: "";
position: absolute;
bottom: 0;
left: 50%;
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-top: 75px solid green;
}
#tree .ornament {
position: absolute;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: red;
}
#tree .ornament:nth-child(1) {
top: 30px;
left: 25px;
}
#tree .ornament:nth-child(2) {
top: 50px;
left: 10px;
}
#tree .ornament:nth-child(3) {
top: 70px;
left: 40px;
}
#tree .ornament:nth-child(4) {
top: 90px;
left: 20px;
}
#tree .ornament:nth-child(5) {
top: 110px;
left: 50px;
}
```
JavaScript:
```javascript
var ornaments = document.querySelectorAll("#tree .ornament");
setInterval(function() {
for (var i = 0; i < ornaments.length; i++) {
var ornament = ornaments[i];
var x = parseInt(ornament.style.left);
var y = parseInt(ornament.style.top);
x += Math.floor(Math.random() * 3) - 1;
y += Math.floor(Math.random() * 3) - 1;
ornament.style.left = x + "px";
ornament.style.top = y + "px";
}
}, 100);
```
这段代码会让圣诞树上的装饰品随机移动。
阅读全文