效果是在顶栏添加一行文本:
JS 代码片段:
// 顶栏倒计时 JS片段 // author by JeffreyChen https://ld246.com/article/1728048965009 (function() { // 清除之前可能的定时器 if (window.__countdownInterval) { clearInterval(window.__countdownInterval); window.__countdownInterval = null; } // 设置标题,替换样式 const baseMessage = '距离<span style="color: red;"> 蓝桥杯 </span>剩余'; const targetDate = new Date('2025-04-14'); const toolbarSelector = '#toolbar > #drag'; let countdownElement = null; // 倒计时元素缓存 let lastDaysLeft = null; // 存储上一次的剩余天数 let initializeAttempts = 0; // 初始化重试计数 function calculateDaysLeft() { const currentDate = new Date(); const differenceInTime = targetDate - currentDate; return Math.max(Math.ceil(differenceInTime / (1000 * 3600 * 24)) - 1, 0); } function updateCountdown() { const daysLeft = calculateDaysLeft(); if (daysLeft !== lastDaysLeft) { // 仅在剩余天数更新时改变 DOM if (countdownElement) { countdownElement.innerHTML = `${baseMessage} ${daysLeft} 天`; lastDaysLeft = daysLeft; // 更新上一次的剩余天数 } } } function insertCountdownElement() { if (!countdownElement) { const toolbarDrag = document.querySelector(toolbarSelector); if (toolbarDrag) { countdownElement = document.getElementById("countdown_days_display"); if (!countdownElement) { toolbarDrag.insertAdjacentHTML( "afterend", `<div id="countdown_days_display" style="font-size: 12px; color: var(--b3-toolbar-color); margin-right: 14px; user-select:none;"> </div>` ); countdownElement = document.getElementById("countdown_days_display"); } updateCountdown(); // 初次载入后立即更新倒计时 initializeAttempts = 0; // 重置初始化重试计数 // 设置新的定时器并保存ID到全局变量 window.__countdownInterval = setInterval(updateCountdown, 60 * 1000); // 每60秒更新一次 } } } function tryInitializeCountdown() { insertCountdownElement(); if (!countdownElement && initializeAttempts < 5) { initializeAttempts++; console.error(`无法找到指定的工具栏挂载点或倒计时元素,第${initializeAttempts}次重试`); setTimeout(tryInitializeCountdown, Math.min(3000 * initializeAttempts, 15000)); // 指数退避重试延迟 } } tryInitializeCountdown(); })();
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于