js实现闪烁效果
使用CSS动画实现闪烁效果
通过CSS的@keyframes规则定义闪烁动画,再利用JavaScript动态添加/移除类名控制效果。
CSS部分:
.blink {
animation: blink 1s infinite;
}
@keyframes blink {
0% { opacity: 1; }
50% { opacity: 0; }
100% { opacity: 1; }
}
JavaScript部分:

const element = document.getElementById('target');
element.classList.add('blink');
// 停止闪烁
function stopBlink() {
element.classList.remove('blink');
}
纯JavaScript定时器实现
通过setInterval和opacity属性切换实现基础闪烁效果:
const element = document.getElementById('target');
let isVisible = true;
const blinkInterval = setInterval(() => {
isVisible = !isVisible;
element.style.opacity = isVisible ? '1' : '0';
}, 500);
// 停止闪烁
clearInterval(blinkInterval);
使用requestAnimationFrame实现高性能闪烁
适合需要平滑动画效果的场景:

const element = document.getElementById('target');
let startTime = null;
let running = true;
function blink(timestamp) {
if (!startTime) startTime = timestamp;
const elapsed = timestamp - startTime;
const progress = (elapsed % 1000) / 1000;
element.style.opacity = Math.abs(progress - 0.5) * 2;
if (running) {
requestAnimationFrame(blink);
}
}
requestAnimationFrame(blink);
// 停止闪烁
function stopBlink() {
running = false;
element.style.opacity = '1';
}
颜色闪烁实现
实现元素背景色或文字颜色的闪烁变化:
const element = document.getElementById('target');
let colors = ['red', 'yellow', 'blue'];
let currentIndex = 0;
setInterval(() => {
currentIndex = (currentIndex + 1) % colors.length;
element.style.color = colors[currentIndex];
}, 300);
带缓动效果的闪烁
使用非线性变化实现更自然的闪烁效果:
const element = document.getElementById('target');
function easeInOutSine(x) {
return -(Math.cos(Math.PI * x) - 1) / 2;
}
function blink() {
const now = Date.now();
const duration = 2000;
const progress = (now % duration) / duration;
const easedProgress = easeInOutSine(progress);
element.style.opacity = Math.sin(easedProgress * Math.PI);
requestAnimationFrame(blink);
}
blink();






