让上面的树叶效果,三张图片随机落下
时间: 2024-01-10 16:25:27 浏览: 24
以下是一个示例代码,实现在页面上同时显示树叶效果和随机落下的图片:
HTML 代码:
```html
<div id="image-container"></div>
<div class="leaves"></div>
```
CSS 代码:
```css
.leaves {
width: 100px;
height: 100px;
background-image: url('https://cdn.pixabay.com/photo/2014/04/03/10/16/leaves-310840_960_720.png');
background-size: cover;
animation: leaf-fall 10s linear infinite;
position: absolute;
top: -100px;
}
@keyframes leaf-fall {
0% {
transform: translateY(-100%);
}
100% {
transform: translateY(100vh);
}
}
```
JavaScript 代码:
```javascript
const images = [
'image1.jpg',
'image2.jpg',
'image3.jpg',
'image4.jpg',
'image5.jpg',
'image6.jpg'
];
const imageContainer = document.getElementById('image-container');
for (let i = 0; i < 3; i++) {
const randomIndex = Math.floor(Math.random() * images.length);
const imageUrl = images[randomIndex];
const img = document.createElement('img');
img.src = imageUrl;
img.style.position = 'absolute';
img.style.top = '-100px';
img.style.left = Math.floor(Math.random() * (window.innerWidth - 100)) + 'px';
imageContainer.appendChild(img);
images.splice(randomIndex, 1);
}
const leaves = document.querySelectorAll('.leaves');
for (let i = 0; i < leaves.length; i++) {
const leaf = leaves[i];
leaf.style.left = Math.floor(Math.random() * (window.innerWidth - 100)) + 'px';
}
```
这段代码首先定义了一个包含图片路径的数组 `images`。然后使用 `for` 循环三次,每次从 `images` 数组中随机选择一个图片路径,并创建一个 `img` 元素,将图片路径设置为 `src` 属性,并将 `img` 元素添加到页面中的 `imageContainer` 容器中。同时,我们还需要设置每个图片元素的位置,使用 `Math.random()` 函数生成一个随机的左边距,同时将 `top` 属性设置为 `-100px`,在页面的最顶部开始落下。
接下来,我们需要将树叶效果和随机落下的图片结合在一起。我们使用 `querySelectorAll()` 方法获取所有的树叶元素,然后使用 `for` 循环遍历每个树叶元素,设置一个随机的左边距,使得树叶效果在页面的不同位置出现。
最后,我们需要为树叶效果添加 CSS 样式,实现树叶从页面的顶部落下。我们使用 `@keyframes` 定义了一个名为 `leaf-fall` 的动画,将树叶从 `-100%` 的位置移动到 `100vh` 的位置,实现树叶从页面顶部落下的效果。