公告栏轮播效果html
时间: 2023-09-26 07:11:10 浏览: 41
以下是一个简单的公告栏轮播效果的 HTML 代码示例:
```html
<div class="notice">
<ul>
<li>公告1</li>
<li>公告2</li>
<li>公告3</li>
<li>公告4</li>
<li>公告5</li>
</ul>
</div>
<style>
.notice {
height: 30px;
overflow: hidden;
position: relative;
}
.notice ul {
list-style: none;
margin: 0;
padding: 0;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
}
.notice li {
flex: 1;
text-align: center;
line-height: 30px;
background-color: #eee;
margin-right: 10px;
}
.notice .active {
background-color: #ccc;
}
</style>
<script>
var noticeList = document.querySelectorAll('.notice li');
var currentIndex = 0;
function changeNotice() {
currentIndex = (currentIndex + 1) % noticeList.length;
for (var i = 0; i < noticeList.length; i++) {
if (i === currentIndex) {
noticeList[i].classList.add('active');
} else {
noticeList[i].classList.remove('active');
}
}
}
setInterval(changeNotice, 3000);
</script>
```
这个示例中,我们使用了一个 `div` 元素作为公告栏的容器,内部使用了一个 `ul` 元素来承载公告列表。每个公告都是一个 `li` 元素。我们通过 CSS 来设置公告栏的高度、隐藏超出部分、设置每个公告的样式等。
在 JavaScript 中,我们通过 `setInterval` 定时器来实现公告栏的轮播效果。我们定义了一个 `currentIndex` 变量来记录当前显示的公告的索引,然后通过 `changeNotice` 函数来切换公告。在 `changeNotice` 函数中,我们先更新 `currentIndex` 变量,然后遍历所有的公告元素,如果当前元素的索引和 `currentIndex` 相同,则添加一个 `active` 类来显示这个公告,否则移除 `active` 类来隐藏这个公告。