js实现520
使用JavaScript实现"520"效果
通过JavaScript可以创建多种与"520"(中文谐音"我爱你")相关的效果,以下是几种常见实现方式:
动态文字效果
创建一个逐渐显示"520"的动画效果:

const text = "520";
let index = 0;
const element = document.getElementById('love-text');
function typeWriter() {
if (index < text.length) {
element.innerHTML += text.charAt(index);
index++;
setTimeout(typeWriter, 300);
}
}
typeWriter();
爱心粒子动画
使用Canvas绘制动态爱心粒子效果:
const canvas = document.getElementById('love-canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const particles = [];
for (let i = 0; i < 100; i++) {
particles.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
size: Math.random() * 5 + 2,
speedX: Math.random() * 3 - 1.5,
speedY: Math.random() * 3 - 1.5
});
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(particle => {
ctx.beginPath();
ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
ctx.fillStyle = '#ff3366';
ctx.fill();
particle.x += particle.speedX;
particle.y += particle.speedY;
if (particle.x < 0 || particle.x > canvas.width) particle.speedX *= -1;
if (particle.y < 0 || particle.y > canvas.height) particle.speedY *= -1;
});
requestAnimationFrame(draw);
}
draw();
数字倒计时
创建一个从5到0的倒计时效果:

let count = 5;
const countdownElement = document.getElementById('countdown');
function countdown() {
if (count >= 0) {
countdownElement.textContent = count === 0 ? '520!' : count;
count--;
setTimeout(countdown, 1000);
}
}
countdown();
交互式爱心生成
点击页面生成随机位置的爱心:
document.addEventListener('click', function(e) {
const heart = document.createElement('div');
heart.classList.add('heart');
heart.innerHTML = '❤️';
heart.style.left = `${e.clientX}px`;
heart.style.top = `${e.clientY}px`;
document.body.appendChild(heart);
setTimeout(() => {
heart.remove();
}, 2000);
});
文字飘散效果
鼠标悬停时文字"520"飘散:
const loveText = document.getElementById('love-text');
loveText.addEventListener('mouseover', function() {
const letters = this.textContent.split('');
this.textContent = '';
letters.forEach((letter, i) => {
const span = document.createElement('span');
span.textContent = letter;
span.style.position = 'relative';
span.style.display = 'inline-block';
span.style.transition = 'all 0.3s ease';
span.style.transform = `translate(${Math.random() * 100 - 50}px, ${Math.random() * 100 - 50}px)`;
this.appendChild(span);
});
});
loveText.addEventListener('mouseout', function() {
const spans = this.querySelectorAll('span');
spans.forEach(span => {
span.style.transform = 'translate(0, 0)';
});
});
这些代码示例可以根据具体需求进行调整和组合,创建出更丰富的"520"效果。实际应用时需要确保HTML中有对应的元素容器,并根据需要添加CSS样式。






