js实现520


以下是几种使用JavaScript实现"520"相关效果的示例代码,涵盖不同场景需求:
动态数字变化效果
const element = document.getElementById('loveNumber');
let count = 0;
const target = 520;
const duration = 2000; // 动画时长2秒
const step = target/(duration/16);
function updateNumber() {
count = Math.min(count + step, target);
element.textContent = Math.floor(count);
if(count < target) requestAnimationFrame(updateNumber);
}
updateNumber();
爱心粒子动画
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');
const particles = [];
for(let i=0; i<520; i++) {
particles.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
size: Math.random() * 5 + 2,
speedX: Math.random() * 2 - 1,
speedY: Math.random() * 2 - 1
});
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'red';
particles.forEach(p => {
p.x += p.speedX;
p.y += p.speedY;
if(p.x < 0 || p.x > canvas.width) p.speedX *= -1;
if(p.y < 0 || p.y > canvas.height) p.speedY *= -1;
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI*2);
ctx.fill();
});
requestAnimationFrame(animate);
}
animate();
网页背景特效
document.body.style.background = 'linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%)';
document.body.style.display = 'flex';
document.body.style.justifyContent = 'center';
document.body.style.alignItems = 'center';
document.body.style.height = '100vh';
const heart = document.createElement('div');
heart.innerHTML = '520';
heart.style.fontSize = '10rem';
heart.style.color = 'white';
heart.style.textShadow = '0 0 20px rgba(255,0,0,0.8)';
heart.style.animation = 'pulse 1s infinite alternate';
document.body.appendChild(heart);
const style = document.createElement('style');
style.textContent = `
@keyframes pulse {
from { transform: scale(1); }
to { transform: scale(1.1); }
}`;
document.head.appendChild(style);
控制台打印特殊效果
console.log('%c520', 'font-size: 50px; color: red; text-shadow: 2px 2px 4px #000;');
console.log('%c❤️', 'font-size: 30px; color: pink;', 'I Love You');
随机位置显示520
setInterval(() => {
const span = document.createElement('span');
span.textContent = '520';
span.style.position = 'fixed';
span.style.left = Math.random() * window.innerWidth + 'px';
span.style.top = Math.random() * window.innerHeight + 'px';
span.style.color = `hsl(${Math.random()*360}, 100%, 50%)`;
span.style.fontSize = Math.random() * 30 + 10 + 'px';
document.body.appendChild(span);
setTimeout(() => {
span.remove();
}, 1000);
}, 100);
这些代码可以直接在浏览器中运行,根据需求选择适合的效果或组合使用。每种实现方式都可通过调整参数来自定义显示效果。






