〇×〇站

个人博客,佛系更新

vue中 满屏雪花降落效果

  • Pluto
  • 2023-04-27 16:22:24
  • 88
  • 转自https://blog.csdn.net/wuxueru100200/article/details/122107901

    1. html

    <template>
    	<div class="box" id="snowzone"></div>
    </template>
    

    2. css(写在 scoped 外面,或者样式加 /deep/,否则类名加上,样式也不会生效)

    .snow_img {
        animation: mymove 5s;
        height: 50px;
        position: absolute;
        opacity: 0;
    }
    @keyframes mymove{
        0%{bottom:100%;opacity:0;}
        50%{opacity:1;transform: rotate(1080deg);}
        100%{transform: rotate(0deg);opacity: 0;bottom:0;}
    }
    

    3. js

    mounted() {
    	var that = this
    	setInterval(() => {
    		var left = Math.random()*window.innerWidth;
    		var height = Math.random()*window.innerHeight;
    		var src = require("../assets/img/s"+Math.floor(Math.random()*2+1)+".png");//两张图片分别为"s1.png"、"s2.png"
    		that.getSnow(left,height,src)
    	},500);
    },
    methods: {
    	// 雪花
    	getSnow(left,height,src) {
    		var div = document.createElement("div");
    		var img = document.createElement("img");
    		img.className = 'snow_img'
    		div.appendChild(img);
    		img.src = src;
    		div.style.position = 'fixed'
    		div.style.left= left+"px";
    		div.style.height= height+"px";
    		document.getElementById("snowzone").appendChild(div);
    		setTimeout(function(){
    			document.getElementById("snowzone").removeChild(div);
    		},5000);
    	},
    }
    

    图片:

    s1.pngs1.png s2.pngs2.png

    实现效果:

    s2.png

    总结:

    动态加上类名不生效的原因:在scoped中定义的类名会解析成这个样子 snow_img[data-v-57bc25a0] ,然而动态添加的类名是 snow_img ,所以样式是不生效的

    分类:
  • 代码
  • 标签:
  • vue