discuz 侧边栏添加一个新闻小工具
<ul id="newsList" class="news-list"></ul>
<div class="micro-word" id="microWord"></div>
<script>
// 获取新闻数据的函数
async function fetchNews() {
try {
const response = await fetch("https://60s.viki.moe/");
const data = await response.json();
displayNews(data.data);
} catch (error) {
console.error("Error fetching news:", error);
document.getElementById("microWord").innerText = "加载新闻失败,请稍后再试。";
document.getElementById("microWord").classList.add("error");
}
}
// 显示新闻的函数
function displayNews(newsArray) {
const newsList = document.getElementById("newsList");
const microWord = document.getElementById("microWord");
// 清空现有内容
newsList.innerHTML = "";
microWord.innerHTML = "";
// 提取新闻和微语
const newsItems = newsArray.filter(item => !item.includes("【微语】")).slice(0, 6); // 限制前10条
const microText = newsArray.find(item => item.includes("【微语】"));
// 添加新闻到列表
newsItems.forEach(item => {
const li = document.createElement("li");
li.textContent = item;
newsList.appendChild(li);
});
// 显示微语
if (microText) {
microWord.textContent = microText;
}
}
// 页面加载时调用获取新闻
window.onload = fetchNews;
</script>
<style>
/* 新闻列表样式 */
.news-list {
list-style: none;
padding: 0;
margin: 0;
}
.news-list li {
padding: 10px 0;
border-bottom: 1px solid #ddd;
}
.news-list li:last-child {
border-bottom: none;
}
/* 微语样式 */
.micro-word {
margin-top: 20px;
font-style: italic;
color: #666;
text-align: center;
}
/* 加载失败提示样式 */
.micro-word.error {
color: #d00;
font-weight: bold;
text-align: center;
}
</style>
页:
[1]