下面是一段基于 jQuery 的前端红包雨活动代码示例:
HTML 代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>红包雨活动</title>
<link rel="stylesheet" href="styles.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="red-envelope-rain">
<div class="cover">
<p>点击屏幕开始</p>
</div>
<div class="envelopes"></div>
</div>
</body>
</html>
CSS 代码:
body {
margin: 0;
padding: 0;
background-color: #f9e5d8;
}
.red-envelope-rain {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.cover {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
color: #d95735;
font-size: 3em;
}
.envelopes {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.envelope {
position: absolute;
width: 50px;
height: 50px;
background-image: url('red-envelope.png');
background-size: cover;
cursor: pointer;
z-index: 1;
}
.envelope:hover {
transform: scale(1.2);
}
.envelope-burst {
position: absolute;
width: 100px;
height: 100px;
background-image: url('red-burst.png');
background-size: cover;
animation: envelope-burst 0.5s linear forwards;
z-index: 2;
}
@keyframes envelope-burst {
from {
transform: scale(0.1);
opacity: 1;
}
to {
transform: scale(1);
opacity: 0;
}
}
JavaScript 代码:
$(function() {
var $rain = $('.red-envelope-rain');
var $cover = $('.cover');
var $envelopes = $('.envelopes');
var timer;
// 点击屏幕开始
$rain.on('click', function() {
$cover.fadeOut();
startRain();
});
// 开始红包雨
function startRain() {
timer = setInterval(function() {
var left = Math.random() * ($rain.width() - 50);
var envelope = $('<div>').addClass('envelope').css({
left: left,
top: '-50px',
});
$envelopes.append(envelope);
envelope.animate({
top: $rain.height() + 'px',
}, 5000, function() {
$(this).remove();
});
}, 500);
}
// 点击抢红包
$envelopes.on('click', '.envelope', function() {
var $this = $(this);
$this.addClass('envelope-burst');
setTimeout(function() {
$this.remove();
}, 500);
});
// 停止红包雨
function stopRain() {
clearInterval(timer);
$envelopes.empty();
}
});
注意:上述代码中的图片路径需要根据实际情况进行修改。