js实现公告
实现公告栏的基本方法
使用HTML和CSS创建公告栏的DOM结构,通过JavaScript动态更新内容。公告栏通常需要滚动效果或定时切换公告。
<div id="notice-bar" style="width: 100%; overflow: hidden;">
<ul id="notice-list" style="list-style: none; padding: 0; margin: 0;">
<li>公告内容1</li>
<li>公告内容2</li>
<li>公告内容3</li>
</ul>
</div>
垂直滚动公告实现
通过改变margin-top属性实现垂直滚动效果,使用setInterval定时器控制滚动速度。
const noticeList = document.getElementById('notice-list');
const items = noticeList.getElementsByTagName('li');
let currentIndex = 0;
const itemHeight = items[0].offsetHeight;
function scrollNotice() {
currentIndex = (currentIndex + 1) % items.length;
noticeList.style.marginTop = `-${currentIndex * itemHeight}px`;
}
setInterval(scrollNotice, 2000); // 每2秒滚动一次
横向滚动公告实现
通过改变transform属性实现横向滚动效果,适合单条较长公告内容。

const noticeBar = document.getElementById('notice-bar');
const noticeContent = document.createElement('div');
noticeContent.textContent = '这是一条重要的公告内容,将会从右向左滚动显示...';
noticeBar.appendChild(noticeContent);
let position = noticeBar.offsetWidth;
function horizontalScroll() {
position--;
if (position < -noticeContent.offsetWidth) {
position = noticeBar.offsetWidth;
}
noticeContent.style.transform = `translateX(${position}px)`;
requestAnimationFrame(horizontalScroll);
}
horizontalScroll();
使用CSS动画实现公告效果
结合CSS3动画可以创建更流畅的公告效果,减少JavaScript负担。
@keyframes scroll {
0% { transform: translateY(0); }
100% { transform: translateY(-100%); }
}
.notice-container {
height: 30px;
overflow: hidden;
}
.notice-list {
animation: scroll 6s infinite;
}
从服务器获取公告内容
通过AJAX或Fetch API从服务器动态获取公告内容并更新显示。

async function fetchNotices() {
try {
const response = await fetch('/api/notices');
const notices = await response.json();
const noticeList = document.getElementById('notice-list');
noticeList.innerHTML = notices.map(notice =>
`<li>${notice.title}: ${notice.content}</li>`
).join('');
} catch (error) {
console.error('获取公告失败:', error);
}
}
fetchNotices();
公告栏交互功能增强
添加鼠标悬停暂停和点击事件处理,提升用户体验。
const noticeBar = document.getElementById('notice-bar');
let scrollInterval;
function startScroll() {
scrollInterval = setInterval(scrollNotice, 2000);
}
function stopScroll() {
clearInterval(scrollInterval);
}
noticeBar.addEventListener('mouseenter', stopScroll);
noticeBar.addEventListener('mouseleave', startScroll);
noticeBar.addEventListener('click', function() {
// 点击公告执行的操作
console.log('公告被点击');
});
startScroll(); // 初始启动滚动
响应式公告栏设计
使用CSS媒体查询确保公告栏在不同设备上显示正常。
#notice-bar {
width: 100%;
height: 40px;
line-height: 40px;
background-color: #f8f8f8;
border: 1px solid #eee;
}
@media (max-width: 768px) {
#notice-bar {
height: 30px;
line-height: 30px;
font-size: 14px;
}
}





