不多说了,直接贴代码
const rain = (tagId) => {
const wid = 40;
function addtag() {
var div = document.createElement("div");
div.className = "red-packet-rain";
let left = Math.random() * window.innerWidth;
if (left > 80) left = left - wid;
left = Math.round(left / wid) * wid;
div.style.left = left + "px";
document.getElementById(tagId).appendChild(div);
setTimeout(function () {
document.getElementById(tagId).removeChild(div);
}, 4000);
}
raintimer = setInterval(() => {
addtag();
}, 600);
};
.red-packet-rain {
position: absolute;
top: 10px;
opacity: 0;
height: 60px;
width: 40px;
padding: 15px;
background: url("../../assets/img/red-packet/red-packet-rain.png")
no-repeat;
background-size: 100% 100%;
animation: drops 2s cubic-bezier(0.54, 0, 0.26, 0.69) infinite;
background-clip:content-box;
}
上面的代码主要实现里向一个父级元素里动态的添加红包雨,会出现红包雨重合的情况,因为红包雨定位的left是随机的。
遇到一个问题,因为项目用的vue框架 ,.red-packet-rain 在局部样式里未生效,因为组件的局部样式有scoped,放到全局样式里就行了。