用vue2写一个会动的背景
时间: 2024-05-08 14:15:24 浏览: 9
以下是使用Vue2实现一个简单的动态背景的示例代码:
```
<template>
<div class="background">
<div class="stars">
<div v-for="star in stars" :key="star.id" class="star" :style="star.style"></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
stars: [],
width: 0,
height: 0
}
},
mounted() {
this.width = window.innerWidth
this.height = window.innerHeight
this.generateStars()
window.addEventListener('resize', this.handleResize)
this.animate()
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
this.width = window.innerWidth
this.height = window.innerHeight
this.generateStars()
},
generateStars() {
this.stars = []
const count = Math.round(this.width * this.height / 10000)
for (let i = 0; i < count; i++) {
const x = Math.random() * this.width
const y = Math.random() * this.height
const size = Math.random() * 3
const opacity = Math.random() * 0.5 + 0.5
const style = {
left: x + 'px',
top: y + 'px',
width: size + 'px',
height: size + 'px',
opacity: opacity
}
this.stars.push({ id: i, style })
}
},
animate() {
this.stars.forEach(star => {
star.style.transform = 'translateY(0px)'
star.style.transition = 'transform 1s'
setTimeout(() => {
star.style.transform = `translateY(${this.height}px)`
star.style.transition = 'none'
}, Math.random() * 5000 + 5000)
})
setTimeout(() => {
this.animate()
}, 10000)
}
}
}
</script>
<style scoped>
.background {
position: relative;
width: 100%;
height: 100%;
}
.stars {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.star {
position: absolute;
border-radius: 50%;
background: rgba(255, 255, 255, 0.8);
}
</style>
```
该示例使用了Vue2的基本特性,包括组件、数据绑定、生命周期钩子、事件监听、计算属性等等。实现了一个会动的背景,包含了多个星星元素,每个星星会在页面中上下飘动。当窗口大小改变时,星星的数量和位置也会随之改变。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)