js实现流光


流光效果实现方法
通过CSS动画和JavaScript动态控制实现元素流光效果,以下是两种常见实现方式:
CSS动画实现基础流光
<div class="light-flow"></div>
.light-flow {
width: 200px;
height: 50px;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.8), transparent);
position: relative;
overflow: hidden;
}
.light-flow::before {
content: "";
position: absolute;
width: 50%;
height: 100%;
background: linear-gradient(90deg, transparent, white, transparent);
animation: flow 2s linear infinite;
}
@keyframes flow {
0% { left: -50%; }
100% { left: 100%; }
}
JavaScript动态控制流光
<button id="flow-btn">流光按钮</button>
const btn = document.getElementById('flow-btn');
btn.addEventListener('mouseenter', () => {
btn.style.position = 'relative';
btn.style.overflow = 'hidden';
const flow = document.createElement('div');
flow.style.position = 'absolute';
flow.style.width = '20px';
flow.style.height = '200%';
flow.style.background = 'linear-gradient(90deg, transparent, rgba(255,255,255,0.7), transparent)';
flow.style.transform = 'rotate(30deg)';
flow.style.left = '-20px';
flow.style.top = '-50%';
flow.style.animation = 'flow 1.5s linear';
btn.appendChild(flow);
setTimeout(() => {
flow.remove();
}, 1500);
});
// 添加CSS
const style = document.createElement('style');
style.textContent = `
@keyframes flow {
0% { left: -20px; }
100% { left: calc(100% + 20px); }
}
`;
document.head.appendChild(style);
高级流光效果实现
跟随鼠标的流光效果
<div id="flow-container"></div>
const container = document.getElementById('flow-container');
container.style.position = 'relative';
container.style.width = '100%';
container.style.height = '300px';
container.style.background = '#222';
container.addEventListener('mousemove', (e) => {
const flow = document.createElement('div');
flow.style.position = 'absolute';
flow.style.width = '100px';
flow.style.height = '100px';
flow.style.borderRadius = '50%';
flow.style.background = 'radial-gradient(circle, rgba(255,255,255,0.8) 0%, transparent 70%)';
flow.style.left = `${e.clientX - 50}px`;
flow.style.top = `${e.clientY - 50}px`;
flow.style.opacity = '1';
flow.style.transition = 'opacity 0.5s ease-out';
container.appendChild(flow);
setTimeout(() => {
flow.style.opacity = '0';
setTimeout(() => flow.remove(), 500);
}, 100);
});
SVG实现复杂流光
<svg id="svg-flow" width="300" height="100">
<defs>
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="transparent" />
<stop offset="50%" stop-color="white" />
<stop offset="100%" stop-color="transparent" />
</linearGradient>
</defs>
<rect id="flow-rect" x="0" y="0" width="100%" height="100%" fill="url(#gradient)" />
</svg>
const rect = document.getElementById('flow-rect');
let pos = -300;
function animate() {
pos = (pos > 600) ? -300 : pos + 2;
rect.setAttribute('x', pos);
requestAnimationFrame(animate);
}
animate();
性能优化建议
- 使用
will-change属性提前告知浏览器元素将发生变化 - 合理使用
requestAnimationFrame代替setInterval - 对频繁创建销毁的元素使用对象池技术
- 避免过多使用滤镜效果(filter)
- 对静态流光效果优先使用CSS实现
以上方法可根据实际需求组合使用,通过调整颜色、速度、尺寸等参数可获得不同风格的流光效果。






