js实现通知滚动
实现通知滚动效果
使用JavaScript实现通知滚动效果可以通过多种方式完成,以下是几种常见的方法:
使用CSS动画结合JavaScript控制
通过CSS的animation属性实现滚动效果,JavaScript用于动态更新内容或控制动画状态。

.notification {
white-space: nowrap;
overflow: hidden;
}
.notification-content {
display: inline-block;
animation: scroll 10s linear infinite;
}
@keyframes scroll {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
const notification = document.querySelector('.notification');
const content = document.querySelector('.notification-content');
// 动态更新内容
content.textContent = '新通知内容';
// 暂停和继续动画
notification.addEventListener('mouseenter', () => {
content.style.animationPlayState = 'paused';
});
notification.addEventListener('mouseleave', () => {
content.style.animationPlayState = 'running';
});
使用JavaScript定时器实现滚动
通过setInterval定时更新元素位置实现滚动效果。
const notification = document.querySelector('.notification');
const content = document.querySelector('.notification-content');
let position = notification.offsetWidth;
function scrollText() {
position--;
content.style.transform = `translateX(${position}px)`;
if (position < -content.offsetWidth) {
position = notification.offsetWidth;
}
}
const intervalId = setInterval(scrollText, 20);
// 控制滚动
notification.addEventListener('mouseenter', () => clearInterval(intervalId));
notification.addEventListener('mouseleave', () => {
intervalId = setInterval(scrollText, 20);
});
使用Marquee标签(不推荐)
虽然HTML5已废弃<marquee>标签,但在某些场景下仍可使用。

<marquee behavior="scroll" direction="left">通知内容</marquee>
使用第三方库
如果需要更复杂的效果,可以考虑使用第三方库如Swiper.js或TinySlider。
import Swiper from 'swiper';
const swiper = new Swiper('.notification-container', {
direction: 'horizontal',
loop: true,
autoplay: {
delay: 1000,
},
});
实现注意事项
- 性能优化:避免频繁的DOM操作,使用CSS动画性能更佳。
- 响应式设计:确保滚动效果在不同屏幕尺寸下正常工作。
- 可访问性:为通知内容添加适当的ARIA属性,确保屏幕阅读器能正确识别。
动态内容更新
若通知内容需要从服务器动态获取,可以使用以下方法:
async function updateNotification() {
const response = await fetch('/api/notifications');
const data = await response.json();
content.textContent = data.message;
// 重置动画
content.style.animation = 'none';
content.offsetHeight; // 触发重绘
content.style.animation = 'scroll 10s linear infinite';
}
setInterval(updateNotification, 60000);
以上方法可根据具体需求选择或组合使用,实现灵活的通知滚动效果。






