效果
为了 方便复用对漂浮物进行了封装
父组件
@param floatImage 图片链接
@param float 子组件
<template>
<div class="root">
<div>111</div>
<float :floatImage="floatImage" v-if="floatImage"></float>
</div>
</template>
<script>
import float from './float.vue'
import floatImage from '../assets/logo.png'
export default {
components: {
float
},
data() {
return {
floatImage: floatImage
}
}
}
</script>
<style lang='scss' scoped>
.root {
width: 100vw;
height: 100vh;
}
</style>
子组件
<template>
<div class="float" ref="root">
</div>
</template>
<script>
export default {
props: {
floatImage: {
typeof: String,
default: ''
}
},
name: 'float',
data() {
return {
timer:null
}
},
computed: {
},
watch: {
},
mounted() {
this.$nextTick(() => {
let root = this.$refs.root
let src = this.floatImage
this.timer=setInterval(() => {
this.isSnow(src, root);
}, 1000);
})
},
methods: {
isSnow(src, root) {
// 获取距离左边多少距离
var left = Math.random() * window.innerWidth;
// 创建图片 dom 片段
var img = document.createElement("img");
// 随机绑定 下方的类
img.className = "roll roll" + Math.floor(Math.random() * 3 + 3) + "";
// 图片地址赋值
img.src = src;
// 图片宽度随机
img.style.width = Math.random() * (1.2 - 0.6) + 0.6 + "rem";
// 高度自适应
img.style.height = "auto";
img.style.left = left + "px";
img.style.bottom = "100%";
// 把img 片段 插入 root 中
root.appendChild(img);
setTimeout(() => {
// 移除
root.removeChild(img)
}, 20000);
}
},
destroyed(){
clearInterval(this.timer)
this.timer = null
},
}
</script>
<style lang='scss'>
.float {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
}
@keyframes mysnow {
0% {
bottom: 100%;
transform: rotate(0deg);
}
100% {
bottom: -10%;
transform: rotate(-30deg);
}
}
@-webkit-keyframes mysnow {
0% {
bottom: 100%;
-webkit-transform: rotate(0deg);
}
100% {
bottom: -10%;
-webkit-transform: rotate(-30deg);
}
}
@-moz-keyframes mysnow {
0% {
bottom: 100%;
-moz-transform: rotate(0deg);
}
100% {
bottom: -10%;
-moz-transform: rotate(-30deg);
}
}
@-ms-keyframes mysnow {
0% {
bottom: 100%;
-ms-transform: rotate(0deg);
}
100% {
bottom: -10%;
-ms-transform: rotate(-30deg);
}
}
@-o-keyframes mysnow {
0% {
bottom: 100%;
-o-transform: rotate(00deg);
}
100% {
bottom: -10%;
-o-transform: rotate(-30deg);
}
}
.roll5 {
position: absolute;
animation: mysnow 20s linear;
-webkit-animation: mysnow 20s linear;
-moz-animation: mysnow 20s linear;
-ms-animation: mysnow 20s linear;
-o-animation: mysnow 20s linear;
}
.roll4 {
position: absolute;
animation: mysnow 12s linear;
-webkit-animation: mysnow 12s linear;
-moz-animation: mysnow 12s linear;
-ms-animation: mysnow 12s linear;
-o-animation: mysnow 12s linear;
}
.roll3 {
position: absolute;
animation: mysnow 8s ease-out;
-webkit-animation: mysnow 8s ease-out;
-moz-animation: mysnow 8s ease-out;
-ms-animation: mysnow 8s ease-out;
-o-animation: mysnow 8s ease-out;
}
.roll {
position: fixed;
z-index: 999999;
}
</style>