溫馨提示×

js怎么實(shí)現(xiàn)文本顯示的公告欄

js
小億
132
2023-08-01 10:43:48
欄目: 編程語言

在JavaScript中,可以使用DOM操作來實(shí)現(xiàn)文本顯示的公告欄。下面是一個簡單的示例:

<!DOCTYPE html>
<html>
<head>
<title>公告欄</title>
<style>
.notice {
width: 400px;
height: 200px;
overflow: hidden;
border: 1px solid #ccc;
padding: 10px;
}
</style>
</head>
<body>
<div class="notice">
<marquee id="noticeText" behavior="scroll" direction="left"></marquee>
</div>
<script>
var noticeText = document.getElementById('noticeText');
var notices = ['公告1', '公告2', '公告3']; // 公告內(nèi)容數(shù)組
function showNotice() {
var index = 0;
setInterval(function() {
noticeText.textContent = notices[index];
index = (index + 1) % notices.length;
}, 3000); // 每隔3秒切換一條公告
}
showNotice();
</script>
</body>
</html>

在上面的示例中,使用marquee標(biāo)簽來實(shí)現(xiàn)公告欄的滾動效果。JavaScript部分定義了一個showNotice函數(shù),用于循環(huán)顯示公告內(nèi)容數(shù)組中的元素。使用setInterval定時器每隔3秒切換一條公告內(nèi)容,直到所有公告都顯示完畢。

注意,marquee標(biāo)簽在HTML5中已被廢棄,不推薦使用。可以使用CSS的animation屬性來代替實(shí)現(xiàn)滾動效果。

0