SoFunction
Updated on 2025-03-01

js+css achieves the red envelope rain effect

This article has shared the specific code for JS implementation of red envelope rain display for your reference. The specific content is as follows

part

The red envelope looks like, write a template on the page first

 <div class="hide">
 <div class="RedPackage__Box js-RedPackageBox" data-txt>
  <img src="./images/" alt="">
 </div>
</div>

Container showing red envelopes

<div class="RedPackage__Main js-RedPackage"></div>

part

const $redPackage = $('.js-RedPackage');
const $redPackageBox = $('.js-RedPackageBox');
const redPackageWidth = $();
const redPackageBoxWidth = $();
//Because the red envelope has an angle rotation problem, it is necessary to calculate it to avoid overflowing the screen after rotationconst basePadding = 30;
const maxLeftPx = redPackageWidth - redPackageBoxWidth - basePadding * 2;
 
//Each red envelope is positioned relative to the parent element, and the hierarchy is set through z-indexlet zIndex = 1;
 
function bindEvent() {
 $('click', '.js-RedPackageBox', function() {
 //Get the data of each red envelope const data = $(this).data('txt');
 }
}
 
//Generate random number of mix-maxfunction getRandom(min, max) {
 return (() * (max - min) + min);
}
 
//Movement of red envelopesfunction redPackageBoxSpeed($el, time) {
 $(
 {
 top: '130%',
 },
 time * 1000,
 function() {
 $();
 }
 );
}
 
//Generate red envelopefunction createRedPackageNode() {
 const $newNode = $(true);
 //The data carried by the red envelope const txt = ();
 (txt);
 $('data-txt', (txt));
 
 //The red envelope randomly rotates -30~30 degrees $({
 'z-index': zIndex++,
 left: getRandom(basePadding, maxLeftPx) + 'px',
 transform: 'rotate(' + getRandom(-30, 30) + 'deg)',
 });
 $($newNode);
 
 redPackageBoxSpeed($newNode, 4);
}
 
//Dynamic creation of red envelopesfunction createRedPackageRain() {
 setInterval(() =&gt; {
 createRedPackageNode();
 }, 300);
}
 
function ready() {
 bindEvent();
 createRedPackageRain();
}
 
ready();

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.