<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS 鼠标点击特效</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #000;
}
.particle {
position: absolute;
width: 5px;
height: 5px;
background-color: #fff;
border-radius: 50%;
pointer-events: none;
}
</style>
</head>
<body>
<script>
const particles = [];
const numParticles = 20;
function createParticle(x, y) {
for (let i = 0; i < numParticles; i++) {
const particle = document.createElement('div');
particle.classList.add('particle');
document.body.appendChild(particle);
const angle = Math.random() * Math.PI * 2;
const speed = Math.random() * 1 + 0.5;
const radius = Math.random() * 2 + 1;
particle.style.left = x + 'px';
particle.style.top = y + 'px';
particle.style.width = radius + 'px';
particle.style.height = radius + 'px';
particles.push({
element: particle,
x,
y,
angle,
speed,
life: 1
});
}
}
function updateParticles() {
for (let i = particles.length - 1; i >= 0; i--) {
const p = particles[i];
p.x += Math.cos(p.angle) * p.speed;
p.y += Math.sin(p.angle) * p.speed;
p.life -= 0.01;
p.element.style.left = p.x + 'px';
p.element.style.top = p.y + 'px';
p.element.style.opacity = p.life;
if (p.life <= 0) {
p.element.remove();
particles.splice(i, 1);
}
}
}
function onMouseClick(event) {
createParticle(event.clientX, event.clientY);
}
document.addEventListener('click', onMouseClick);
setInterval(updateParticles, 30);
</script>
</body>
</html>
.particle 类,用于创建圆形粒子,并设置了页面背景颜色为黑色。particles 数组用于存储所有的粒子对象。createParticle 函数根据鼠标点击位置创建多个粒子,每个粒子都有随机的角度、速度和大小。updateParticles 函数负责更新粒子的位置和透明度,并在粒子生命周期结束时移除它们。onMouseClick 事件监听器捕获鼠标点击事件,并调用 createParticle 函数。setInterval 每 30 毫秒调用一次 updateParticles 来更新粒子状态。这个代码实现了一个简单的鼠标点击特效,点击页面时会在点击位置生成一些粒子并逐渐消失。
上一篇:js 修改title
下一篇:js 鼠标点击事件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站