首先,先看看效果:
实现步骤如下:
1.我们先写结构,代码如下:
<!-- 大红包 -->
<div class="bigBox"><img src="./img/red.png" alt=""></div>
<div class="box">
<!-- 红包雨的视口 -->
<div class="content"></div>
<div class="redBox">
<img src="./img/red.png" alt="">
</div>
<div class="time">10s</div>
</div>
2.写css样式
该红包雨是先有一个大红包,然后进行点击才有小红包落下;
所以小红包刚开始的时候隐藏起来,大红包调至视口居中的位置;
css代码如下:
* {
margin: 0;
padding: 0;
}.bigBox {
width: 250px;
height: 300px;
margin: 300px auto;
transform-origin: 125px 250pxs;
animation: spin .5s ease infinite;
}.bigBox img {
width: 250px;
height: 300px;
cursor: pointer;
}
.box{
display: none;
}
.content {
position: relative;
overflow: hidden;
}
.redBox {
width: 50px;
height: 70px;
position: absolute;
top: -70px;
}
.redBox img {
width: 50px;
height: 70px;
}
.time {
position: absolute;
right: 30px;
bottom: 30px;
}/* 大红包动画 */
@keyframes spin {
0% {
transform: rotate(-30deg);
}50% {
transform: rotate(30deg);
}100% {
transform: rotate(-30deg);
}
}
3.此时导入jQuery的代码并开始写红包雨的动画
具体代码如下:
// 获取小红包及宽高
var redBox = $('.redBox')
var redWidth = redBox.innerWidth()
var redHeight = redBox.innerHeight()
//大红包点击事件
//当点击大红包的时候,大红包隐藏,包裹小红包的盒子就显示,并执行小红包动画
$(".bigBox").click(function () {
$(this).css({ display: 'none' })
$(".box").css({ display: 'block' })
getDown()
})
//封装 随机数
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min) + min)
}
//封装红包掉落的动画
function getDown() {
// 获取视口的宽高
var boxWidth = $(window).innerWidth();
var boxHeight = $(window).innerHeight()
//获取掉落小红包包裹的盒子
var content = $(".content")
// 将视口的宽高赋值给包裹的盒子
content.css({ 'width': boxWidth + 'px', 'height': boxHeight + 'px' })
var timer;
var timers;
var zIndex = 1;
//定时器
timer = setInterval(function () {
//克隆小红包
var newRed = redBox.clone(true)
//设置出现的位置以及旋转角度
newRed.css(
{
'left': getRandom(0, boxWidth - redWidth) + 'px',
'z-index': zIndex++,
'transform': 'rotate(' + getRandom(-30, 30) + 'deg)'
}
)
//添加
content.append(newRed)
//动画及删除
newRed.animate(
{ top: boxHeight + 'px' },
3000,
function () {
newRed.remove()
}
)
}, 30)
//时间
var count = 10;
timers = setInterval(function () {
if (count > 0) {
count--;
$(".time").text(count + "s")
} else {
clearInterval(timer, timers)
}
}, 1000)
}
此时代码写完,效果如下: