放到页面上看到的是五张白底小卡:每张一个图标、一个数字、一个彩色圆标签。但这段代码里的 HTML 其实只有两行——<div id="hmM"> 套一个空的 <div class="stats-grid" id="hmM-grid">。卡片、样式、数字都不写在 HTML 里,全由后面那段 <script> 生成。这是一组维形筑网的站点统计卡片。
所以读它得顺着脚本的执行顺序往下走:先注入样式表、再拼出五个格子、然后取数填值、最后量宽度防溢出。下面按这个顺序,把源码里能数出来的地方对一遍。
原版 · 实际效果
<!--
WP 侧边栏 · 中段(站点统计 2+3)· 独立一段
★ 单独粘进一个「外观 → 小工具 → 自定义 HTML」即可,不需要任何父容器 CSS。
★ 自适应:基础样式就是「窄侧边栏」紧凑态(上排 2 张大卡、下排 3 张小卡不变),
小工具变宽时按自身宽度自动放大(容器查询,按小工具宽度算,不按屏幕宽度)。
★ 与左/右段完全独立:CSS 前缀 hmM、DOM id hmM-*,同页不冲突。
★ 数字默认隐藏「—」:贴到博客后由 WordPress 官方 REST 读到真实值才显示;
接口读不到就一直保持「—」,不会出现 1404 / 2587 这类假数字。
★ 只改脚本顶部 CONFIG:
daysMode / daysValue 运行时间现在默认 fixed = 1 天;
想按建站日自动算就改回 'auto' 并填 startDate
reveal false = 直接显示 fallbacks 里的固定数字
base WP 装在子目录填 '/blog';跨域填完整域名
theme mist | candy | mono
★ 数据全部走 WP 自带 REST,无需插件/密钥/改 functions.php:
/wp/v2/posts 读今日更新、本周更新、文章数目;/wp/v2/users 读注册用户。
/wp-json/ 不通会自动改试 /?rest_route=/...
※ WP 对未登录访客只公开「有已发布文章的作者」,故该数是公开作者数。
★ 若编辑器过滤 <script>,把脚本内容用 WPCode / Insert Headers and Footers 插到页脚。
-->
<div id="hmM">
<div class="stats-grid" id="hmM-grid"></div>
</div>
<script>
(function () {
'use strict';
/* ========== 配置(★ 只改这一段) ========== */
var CONFIG = {
startDate: '2020-11-25', // 建站日 YYYY-MM-DD(daysMode='fixed' 时不生效)
daysMode: 'fixed', // 'fixed' 显示 daysValue | 'auto' 按建站日算
daysValue: 1, // ★ 当前默认 = 1 天
reveal: true, // true=先隐藏「—」,读到真实值才显示;false=显示下面固定值
fallbacks: { today: 0, week: 2, posts: 1404, users: 2587, days: 1 },
base: '', // 同域根目录留空;WP 在子目录填 '/blog';跨域填完整域名
theme: 'mist' // mist | candy | mono
};
var CARDS = [
{ key: 'today', icon: 'calendar', label: '今日更新', unit: '篇' },
{ key: 'week', icon: 'calendar7', label: '本周更新', unit: '篇' },
{ key: 'posts', icon: 'file', label: '文章数目', unit: '篇' },
{ key: 'users', icon: 'crown', label: '注册用户', unit: '位' },
{ key: 'days', icon: 'clock', label: '运行时间', unit: '天' }
];
var root = document.getElementById('hmM');
var statsGrid = document.getElementById('hmM-grid');
if (!root || !statsGrid) return;
root.setAttribute('data-theme', CONFIG.theme);
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
/* 样式:窄栏优先。基础即侧边栏紧凑态,宽了再按容器放大。 */
if (!document.getElementById('hmM-css')) {
var css = `
#hmM{container-type:inline-size;container-name:wsM;box-sizing:border-box;
width:100%;margin:0;--card:#fff;--ink:#3f444d;--sub:#4a5059;
--shadow:0 2px 12px rgba(30,40,60,.05);
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif}
#hmM,#hmM *{box-sizing:border-box}
#hmM[data-theme="mist"]{--a1:#4f7fe8;--ab1:#e9f0ff;--a2:#2aa785;--ab2:#e5f6f0;
--a3:#d98a3c;--ab3:#fcf0e2;--a4:#8a70d4;--ab4:#f0ecfb;--a5:#d96a72;--ab5:#fcebed}
#hmM[data-theme="candy"]{--a1:#d9668a;--ab1:#fdeef3;--a2:#d97a86;--ab2:#fdf0f0;
--a3:#dd8a5c;--ab3:#fdf1e9;--a4:#b174c0;--ab4:#f7edfa;--a5:#d9668a;--ab5:#fdeef3}
#hmM[data-theme="mono"]{--a1:#5b6b82;--ab1:#eef1f5;--a2:#5b6b82;--ab2:#eef1f5;
--a3:#5b6b82;--ab3:#eef1f5;--a4:#5b6b82;--ab4:#eef1f5;--a5:#5b6b82;--ab5:#eef1f5}
#hmM[data-dark="1"]{--card:#222834;--ink:#e9edf4;--sub:#c9d1de;
--shadow:0 2px 12px rgba(0,0,0,.28)}
/* 原版 2+3:上排 2 张 span 3、下排 3 张 span 2,行高按内容自然撑满 */
#hmM .stats-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:7px;
grid-template-rows:repeat(2,minmax(94px,auto))}
#hmM .ws-card{grid-column:span 3;min-width:0;background:var(--card);border-radius:13px;
padding:10px 4px 9px;box-shadow:var(--shadow);
display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;
transition:transform .2s,box-shadow .2s}
#hmM .ws-card:nth-child(3),#hmM .ws-card:nth-child(4),#hmM .ws-card:nth-child(5){grid-column:span 2}
#hmM .ws-card:nth-child(1){--c:var(--a1);--cb:var(--ab1)}
#hmM .ws-card:nth-child(2){--c:var(--a2);--cb:var(--ab2)}
#hmM .ws-card:nth-child(3){--c:var(--a3);--cb:var(--ab3)}
#hmM .ws-card:nth-child(4){--c:var(--a4);--cb:var(--ab4)}
#hmM .ws-card:nth-child(5){--c:var(--a5);--cb:var(--ab5)}
#hmM .ws-card:hover{transform:translateY(-3px);box-shadow:0 8px 22px rgba(30,40,60,.09)}
#hmM .ws-ico{width:28px;height:28px;flex:0 0 28px;border-radius:9px;background:var(--cb);
color:var(--c);display:grid;place-items:center;overflow:hidden}
#hmM .ws-ico svg{width:16px;height:16px;display:block}
#hmM .ws-ico img{width:100%;height:100%;object-fit:cover}
#hmM .ws-ico span{font-size:16px;line-height:1}
#hmM .ws-num{color:var(--ink);font-size:clamp(13px,4.4cqw,18px);font-weight:800;line-height:1.1;
letter-spacing:-.5px;white-space:nowrap;font-variant-numeric:tabular-nums;max-width:100%}
#hmM .ws-num [data-num].pending{color:var(--sub);opacity:.4;font-weight:600}
#hmM .ws-unit{font-size:.6em;font-weight:700;margin-left:3px}
#hmM .ws-tag{font-size:10px;font-weight:600;color:var(--c);background:var(--cb);
border-radius:999px;padding:3px 7px;white-space:nowrap;line-height:1.2}
#hmM[data-theme="candy"] .ws-tag{color:#fff;
background:linear-gradient(135deg,var(--c),color-mix(in srgb,var(--c) 62%,#fff))}
#hmM[data-dark="1"] .ws-ico,#hmM[data-dark="1"] .ws-tag{background:rgba(255,255,255,.08)}
#hmM[data-dark="1"] .ws-tag{color:color-mix(in srgb,var(--c) 72%,#fff)}
/* 侧边栏较宽:放大回原版比例 */
@container wsM (min-width:420px){
#hmM .stats-grid{gap:10px;grid-template-rows:repeat(2,minmax(106px,1fr))}
#hmM .ws-card{border-radius:14px;padding:14px 6px 12px;gap:8px}
#hmM .ws-ico{width:34px;height:34px;flex-basis:34px;border-radius:11px}
#hmM .ws-ico svg{width:19px;height:19px}
#hmM .ws-ico span{font-size:18px}
#hmM .ws-num{font-size:clamp(16px,4.8cqw,22px)}
#hmM .ws-tag{font-size:11px;padding:4px 10px}
}
/* 极窄侧边栏:再收一档,标签和数字都不会撑破卡片 */
@container wsM (max-width:230px){
#hmM .stats-grid{gap:5px}
#hmM .ws-card{padding:8px 3px 8px;gap:5px}
#hmM .ws-ico{width:24px;height:24px;flex-basis:24px}
#hmM .ws-ico svg{width:14px;height:14px}
#hmM .ws-tag{font-size:9px;padding:3px 5px}
}
@media (prefers-reduced-motion:reduce){
#hmM .ws-card{transition:none!important}#hmM .ws-card:hover{transform:none}}
`;
var st = document.createElement('style');
st.id = 'hmM-css';
st.textContent = css;
(document.head || document.documentElement).appendChild(st);
}
/* ========== 图标 ========== */
var S = 'fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"';
var ICONS = {
calendar: '<svg viewBox="0 0 24 24" ' + S + '><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18M7 14h.01M12 14h.01M17 14h.01M7 18h.01M12 18h.01"/></svg>',
calendar7: '<svg viewBox="0 0 24 24" ' + S + '><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18"/><text x="12" y="18.2" text-anchor="middle" font-size="9" font-weight="700" fill="currentColor" stroke="none">7</text></svg>',
file: '<svg viewBox="0 0 24 24" ' + S + '><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8M8 17h5"/></svg>',
crown: '<svg viewBox="0 0 24 24" ' + S + '><path d="M3 8l4 4 5-7 5 7 4-4-2 11H5z"/><path d="M5 20h14"/></svg>',
clock: '<svg viewBox="0 0 24 24" ' + S + '><path d="M3.5 12a8.5 8.5 0 1 0 2.6-6.1M3 4v4h4"/><path d="M12 7.5V12l3 2"/></svg>'
};
function esc(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
});
}
function iconHTML(v) {
if (ICONS[v]) return ICONS[v];
if (/^<svg[\s>]/i.test(v)) return v;
if (/^(https?:\/\/|\/|\.\/)/i.test(v) || /\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(v))
return '<img src="' + esc(v) + '" alt="">';
return '<span>' + esc(v || '★') + '</span>';
}
CARDS.forEach(function (c) {
var el = document.createElement('div');
el.className = 'ws-card';
var init = CONFIG.reveal ? '—' : CONFIG.fallbacks[c.key];
el.innerHTML = '<div class="ws-ico">' + iconHTML(c.icon) + '</div>' +
'<div class="ws-num"><span data-num="' + c.key + '"' +
(CONFIG.reveal ? ' class="pending"' : '') + '>' + init + '</span>' +
'<span class="ws-unit">' + esc(c.unit) + '</span></div>' +
'<div class="ws-tag">' + esc(c.label) + '</div>';
statsGrid.appendChild(el);
});
/* ========== 数字:只有拿到真实值才现身 ========== */
function setNum(key, val) {
if (val === null || val === undefined || isNaN(val)) return;
var el = root.querySelector('[data-num="' + key + '"]');
if (!el) return;
val = Math.max(0, Math.round(val));
el.classList.remove('pending');
var from = parseInt(el.textContent, 10);
if (isNaN(from) || reduce) { el.textContent = val; fit(); return; }
var t0 = performance.now();
(function step(t) {
var p = Math.min(1, (t - t0) / 600), e = 1 - Math.pow(1 - p, 3);
el.textContent = Math.round(from + (val - from) * e);
if (p < 1) requestAnimationFrame(step); else fit();
})(performance.now());
}
/* ========== 运行天数 ========== */
function runDays() {
if (CONFIG.daysMode === 'fixed') return parseInt(CONFIG.daysValue, 10) || 0;
var p = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(CONFIG.startDate);
if (!p) return null;
var d = new Date();
return Math.max(0, Math.round((Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) -
Date.UTC(+p[1], +p[2] - 1, +p[3])) / 86400000));
}
/* ========== WordPress 官方 REST(无需插件/密钥/PHP) ========== */
function restUrls(p) {
var b = CONFIG.base || '', i = p.indexOf('?');
var path = i < 0 ? p : p.slice(0, i), tail = i < 0 ? '' : '&' + p.slice(i + 1);
return [b + '/wp-json/wp/v2/' + p, b + '/?rest_route=/wp/v2/' + path + tail];
}
function firstResp(urls, ok) {
var i = 0;
return (function next() {
if (i >= urls.length) return Promise.resolve(null);
var u = urls[i++];
return fetch(u, { headers: { Accept: 'application/json' } })
.then(function (r) { return r.ok ? r : null; })
.catch(function () { return null; })
.then(function (r) { return (r && (!ok || ok(r))) ? r : next(); });
})();
}
function total(query) {
return firstResp(restUrls('posts?per_page=1&_fields=id&' + (query || '')),
function (r) { return r.headers.get('X-WP-Total') !== null; })
.then(function (r) { return r ? parseInt(r.headers.get('X-WP-Total'), 10) : null; });
}
function wpTime(d) {
return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 19);
}
function monday(d) {
var x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
return x;
}
function loadStats() {
var now = new Date();
Promise.all([
total('after=' + encodeURIComponent(wpTime(new Date(now.getFullYear(), now.getMonth(), now.getDate())))),
total('after=' + encodeURIComponent(wpTime(monday(now)))),
total(''),
firstResp(restUrls('users?per_page=1&_fields=id'),
function (r) { return r.headers.get('X-WP-Total') !== null; })
.then(function (r) { return r ? parseInt(r.headers.get('X-WP-Total'), 10) : null; })
]).then(function (r) {
setNum('today', r[0]);
setNum('week', r[1]);
setNum('posts', r[2]);
setNum('users', r[3]); /* 读不到就保持「—」,不填假数字 */
});
}
/* ========== 防溢出 + 深浅色 ========== */
function fit() {
Array.prototype.slice.call(root.querySelectorAll('.ws-num')).forEach(function (el) {
el.style.fontSize = '';
var box = el.closest ? el.closest('.ws-card') : null;
if (!box || !box.clientWidth) return;
var avail = box.clientWidth - 10;
if (avail <= 0) return;
var base = parseFloat(getComputedStyle(el).fontSize) || 16;
var need = el.scrollWidth;
if (need > avail + 1 && need > 0)
el.style.fontSize = Math.max(11, base * avail / need * 0.97).toFixed(1) + 'px';
});
}
var mq = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
function applyDark() {
var h = document.documentElement, b = document.body;
var f = [h.className, b && b.className, h.getAttribute('data-theme'),
h.getAttribute('data-color-scheme'), b && b.getAttribute('data-theme')].join(' ');
var dark = /\bdark\b|dark-mode|theme-dark|night-mode|\bnight\b/i.test(f) ||
(!/\blight\b/i.test(f) && mq && mq.matches);
if (dark) root.setAttribute('data-dark', '1'); else root.removeAttribute('data-dark');
}
/* ========== 启动 ========== */
setNum('days', runDays());
loadStats();
fit();
applyDark();
if (mq) {
if (mq.addEventListener) mq.addEventListener('change', applyDark);
else if (mq.addListener) mq.addListener(applyDark);
}
var lastW = 0;
function onResize() {
var w = root.clientWidth;
if (!w || w === lastW) return;
lastW = w; fit();
}
if (window.ResizeObserver) new ResizeObserver(onResize).observe(root);
else window.addEventListener('resize', onResize);
})();
</script>① HTML 部分只有两个空容器
脚本开头取 document.getElementById('hmM') 和 getElementById('hmM-grid'),紧跟一句 if (!root || !statsGrid) return;。容器不在,脚本直接退出,页面上什么都不会出现。第一处写入是 root.setAttribute('data-theme', CONFIG.theme)。
② 样式不在 <style> 里,在模板字符串里
var css = `...` 之后是 document.createElement('style')、st.id = 'hmM-css'、st.textContent = css,再 appendChild 到 document.head || document.documentElement。插入前用 document.getElementById('hmM-css') 判重。整张样式表的每条选择器都以 #hmM 开头,另有一条 #hmM,#hmM *{box-sizing:border-box},没有 html、body 或裸 * 选择器。
③ 五张卡是 forEach 拼出来的
CARDS 是五个对象;forEach 里 createElement('div')、className = 'ws-card'、用 innerHTML 拼出 .ws-ico / .ws-num / .ws-tag 三段,再 statsGrid.appendChild(el)。图标来自 ICONS 里的 5 段 SVG 字符串,iconHTML() 还留了自定义 svg、图片 URL、纯文字三条分支。初始文本是 CONFIG.reveal ? '—' : CONFIG.fallbacks[c.key],当前 reveal 为 true,所以 fallbacks 里那组 1404 / 2587 只是存在数组里,渲染时取不到。
④ 六列网格怎么排成两行
grid-template-columns:repeat(6,minmax(0,1fr)),.ws-card 默认 grid-column:span 3,第 3~5 张被单独改成 span 2。第一行 3+3=6,第二行 2+2+2=6,两行刚好填满;grid-template-rows:repeat(2,minmax(94px,auto)) 给每行一个下限,卡片高度由内容撑开,底边自然对齐。
⑤ 断点挂在容器上,不是屏幕
根元素写了 container-type:inline-size;container-name:wsM。全段只有 @container wsM (min-width:420px) 和 @container wsM (max-width:230px) 两档,字号用 clamp(13px,4.4cqw,18px)。@media 只有一条 prefers-reduced-motion:reduce,按屏幕宽度的断点 0 条。
⑥ 数字读的是响应头
restUrls(p) 把 ? 切开,返回 /wp-json/wp/v2/ 与 /?rest_route=/wp/v2/ 两个候选,后者把 ? 后面的参数用 & 接上。firstResp 逐个 fetch,失败 catch 成 null 再试下一个;total(query) 请求 posts?per_page=1&_fields=id&after=...,只要 r.headers.get('X-WP-Total') 不为空就 parseInt。loadStats() 用 Promise.all 并取四个值:当天零点之后、本周一之后、全部文章、以及 users 的总数。setNum() 第一行 if (val === null || val === undefined || isNaN(val)) return;,有值才 Math.round 后用 600ms 三次缓动写入;runDays() 是唯一不经过网络的一格。
修复版 · 只动三处
下面这版不改任何文案、数字、配色和取数路径,只补三个在源码里能直接指出的兜底。
<!--
WP 侧边栏 · 中段(站点统计 2+3)· 独立一段
★ 单独粘进一个「外观 → 小工具 → 自定义 HTML」即可,不需要任何父容器 CSS。
★ 自适应:基础样式就是「窄侧边栏」紧凑态(上排 2 张大卡、下排 3 张小卡不变),
小工具变宽时按自身宽度自动放大(容器查询,按小工具宽度算,不按屏幕宽度)。
★ 与左/右段完全独立:CSS 前缀 hmM、DOM id hmM-*,同页不冲突。
★ 数字默认隐藏「—」:贴到博客后由 WordPress 官方 REST 读到真实值才显示;
接口读不到就一直保持「—」,不会出现 1404 / 2587 这类假数字。
★ 只改脚本顶部 CONFIG:
daysMode / daysValue 运行时间现在默认 fixed = 1 天;
想按建站日自动算就改回 'auto' 并填 startDate
reveal false = 直接显示 fallbacks 里的固定数字
base WP 装在子目录填 '/blog';跨域填完整域名
theme mist | candy | mono
★ 数据全部走 WP 自带 REST,无需插件/密钥/改 functions.php:
/wp/v2/posts 读今日更新、本周更新、文章数目;/wp/v2/users 读注册用户。
/wp-json/ 不通会自动改试 /?rest_route=/...
※ WP 对未登录访客只公开「有已发布文章的作者」,故该数是公开作者数。
★ 若编辑器过滤 <script>,把脚本内容用 WPCode / Insert Headers and Footers 插到页脚。
-->
<div id="hmM">
<div class="stats-grid" id="hmM-grid"></div>
</div>
<script>
(function () {
'use strict';
/* ========== 配置(★ 只改这一段) ========== */
var CONFIG = {
startDate: '2020-11-25', // 建站日 YYYY-MM-DD(daysMode='fixed' 时不生效)
daysMode: 'fixed', // 'fixed' 显示 daysValue | 'auto' 按建站日算
daysValue: 1, // ★ 当前默认 = 1 天
reveal: true, // true=先隐藏「—」,读到真实值才显示;false=显示下面固定值
fallbacks: { today: 0, week: 2, posts: 1404, users: 2587, days: 1 },
base: '', // 同域根目录留空;WP 在子目录填 '/blog';跨域填完整域名
theme: 'mist' // mist | candy | mono
};
var CARDS = [
{ key: 'today', icon: 'calendar', label: '今日更新', unit: '篇' },
{ key: 'week', icon: 'calendar7', label: '本周更新', unit: '篇' },
{ key: 'posts', icon: 'file', label: '文章数目', unit: '篇' },
{ key: 'users', icon: 'crown', label: '注册用户', unit: '位' },
{ key: 'days', icon: 'clock', label: '运行时间', unit: '天' }
];
var root = document.getElementById('hmM');
var statsGrid = document.getElementById('hmM-grid');
if (!root || !statsGrid) return;
root.setAttribute('data-theme', CONFIG.theme);
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
/* 样式:窄栏优先。基础即侧边栏紧凑态,宽了再按容器放大。 */
if (!document.getElementById('hmM-css')) {
var css = `
#hmM{container-type:inline-size;container-name:wsM;box-sizing:border-box;
width:100%;margin:0;--card:#fff;--ink:#3f444d;--sub:#4a5059;
--shadow:0 2px 12px rgba(30,40,60,.05);
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif}
#hmM,#hmM *{box-sizing:border-box}
#hmM[data-theme="mist"]{--a1:#4f7fe8;--ab1:#e9f0ff;--a2:#2aa785;--ab2:#e5f6f0;
--a3:#d98a3c;--ab3:#fcf0e2;--a4:#8a70d4;--ab4:#f0ecfb;--a5:#d96a72;--ab5:#fcebed}
#hmM[data-theme="candy"]{--a1:#d9668a;--ab1:#fdeef3;--a2:#d97a86;--ab2:#fdf0f0;
--a3:#dd8a5c;--ab3:#fdf1e9;--a4:#b174c0;--ab4:#f7edfa;--a5:#d9668a;--ab5:#fdeef3}
#hmM[data-theme="mono"]{--a1:#5b6b82;--ab1:#eef1f5;--a2:#5b6b82;--ab2:#eef1f5;
--a3:#5b6b82;--ab3:#eef1f5;--a4:#5b6b82;--ab4:#eef1f5;--a5:#5b6b82;--ab5:#eef1f5}
#hmM[data-dark="1"]{--card:#222834;--ink:#e9edf4;--sub:#c9d1de;
--shadow:0 2px 12px rgba(0,0,0,.28)}
/* 原版 2+3:上排 2 张 span 3、下排 3 张 span 2,行高按内容自然撑满 */
#hmM .stats-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:7px;
grid-template-rows:repeat(2,minmax(94px,auto))}
#hmM .ws-card{grid-column:span 3;min-width:0;background:var(--card);border-radius:13px;
padding:10px 4px 9px;box-shadow:var(--shadow);
display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;
transition:transform .2s,box-shadow .2s}
#hmM .ws-card:nth-child(3),#hmM .ws-card:nth-child(4),#hmM .ws-card:nth-child(5){grid-column:span 2}
#hmM .ws-card:nth-child(1){--c:var(--a1);--cb:var(--ab1)}
#hmM .ws-card:nth-child(2){--c:var(--a2);--cb:var(--ab2)}
#hmM .ws-card:nth-child(3){--c:var(--a3);--cb:var(--ab3)}
#hmM .ws-card:nth-child(4){--c:var(--a4);--cb:var(--ab4)}
#hmM .ws-card:nth-child(5){--c:var(--a5);--cb:var(--ab5)}
#hmM .ws-card:hover{transform:translateY(-3px);box-shadow:0 8px 22px rgba(30,40,60,.09)}
#hmM .ws-ico{width:28px;height:28px;flex:0 0 28px;border-radius:9px;background:var(--cb);
color:var(--c);display:grid;place-items:center;overflow:hidden}
#hmM .ws-ico svg{width:16px;height:16px;display:block}
#hmM .ws-ico img{width:100%;height:100%;object-fit:cover}
#hmM .ws-ico span{font-size:16px;line-height:1}
#hmM .ws-num{color:var(--ink);font-size:clamp(13px,4.4cqw,18px);font-weight:800;line-height:1.1;
letter-spacing:-.5px;white-space:nowrap;font-variant-numeric:tabular-nums;max-width:100%}
#hmM .ws-num [data-num].pending{color:var(--sub);opacity:.4;font-weight:600}
#hmM .ws-unit{font-size:.6em;font-weight:700;margin-left:3px}
#hmM .ws-tag{font-size:10px;font-weight:600;color:var(--c);background:var(--cb);
border-radius:999px;padding:3px 7px;white-space:nowrap;line-height:1.2}
#hmM[data-theme="candy"] .ws-tag{color:#fff;
background:var(--c);
background:linear-gradient(135deg,var(--c),color-mix(in srgb,var(--c) 62%,#fff))}
#hmM[data-dark="1"] .ws-ico,#hmM[data-dark="1"] .ws-tag{background:rgba(255,255,255,.08)}
#hmM[data-dark="1"] .ws-tag{color:color-mix(in srgb,var(--c) 72%,#fff)}
/* 侧边栏较宽:放大回原版比例 */
@container wsM (min-width:420px){
#hmM .stats-grid{gap:10px;grid-template-rows:repeat(2,minmax(106px,1fr))}
#hmM .ws-card{border-radius:14px;padding:14px 6px 12px;gap:8px}
#hmM .ws-ico{width:34px;height:34px;flex-basis:34px;border-radius:11px}
#hmM .ws-ico svg{width:19px;height:19px}
#hmM .ws-ico span{font-size:18px}
#hmM .ws-num{font-size:clamp(16px,4.8cqw,22px)}
#hmM .ws-tag{font-size:11px;padding:4px 10px}
}
/* 极窄侧边栏:再收一档,标签和数字都不会撑破卡片 */
@container wsM (max-width:230px){
#hmM .stats-grid{gap:5px}
#hmM .ws-card{padding:8px 3px 8px;gap:5px}
#hmM .ws-ico{width:24px;height:24px;flex-basis:24px}
#hmM .ws-ico svg{width:14px;height:14px}
#hmM .ws-tag{font-size:9px;padding:3px 5px}
}
@media (prefers-reduced-motion:reduce){
#hmM .ws-card{transition:none!important}#hmM .ws-card:hover{transform:none}}
`;
var st = document.createElement('style');
st.id = 'hmM-css';
st.textContent = css;
(document.head || document.documentElement).appendChild(st);
}
/* ========== 图标 ========== */
var S = 'fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"';
var ICONS = {
calendar: '<svg viewBox="0 0 24 24" ' + S + '><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18M7 14h.01M12 14h.01M17 14h.01M7 18h.01M12 18h.01"/></svg>',
calendar7: '<svg viewBox="0 0 24 24" ' + S + '><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18"/><text x="12" y="18.2" text-anchor="middle" font-size="9" font-weight="700" fill="currentColor" stroke="none">7</text></svg>',
file: '<svg viewBox="0 0 24 24" ' + S + '><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8M8 17h5"/></svg>',
crown: '<svg viewBox="0 0 24 24" ' + S + '><path d="M3 8l4 4 5-7 5 7 4-4-2 11H5z"/><path d="M5 20h14"/></svg>',
clock: '<svg viewBox="0 0 24 24" ' + S + '><path d="M3.5 12a8.5 8.5 0 1 0 2.6-6.1M3 4v4h4"/><path d="M12 7.5V12l3 2"/></svg>'
};
function esc(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
});
}
function iconHTML(v) {
if (ICONS[v]) return ICONS[v];
if (/^<svg[\s>]/i.test(v)) return v;
if (/^(https?:\/\/|\/|\.\/)/i.test(v) || /\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(v))
return '<img src="' + esc(v) + '" alt="">';
return '<span>' + esc(v || '★') + '</span>';
}
CARDS.forEach(function (c) {
var el = document.createElement('div');
el.className = 'ws-card';
var init = CONFIG.reveal ? '—' : CONFIG.fallbacks[c.key];
el.innerHTML = '<div class="ws-ico">' + iconHTML(c.icon) + '</div>' +
'<div class="ws-num"><span data-num="' + c.key + '"' +
(CONFIG.reveal ? ' class="pending"' : '') + '>' + init + '</span>' +
'<span class="ws-unit">' + esc(c.unit) + '</span></div>' +
'<div class="ws-tag">' + esc(c.label) + '</div>';
statsGrid.appendChild(el);
});
/* ========== 数字:只有拿到真实值才现身 ========== */
function setNum(key, val) {
if (val === null || val === undefined || isNaN(val)) return;
var el = root.querySelector('[data-num="' + key + '"]');
if (!el) return;
val = Math.max(0, Math.round(val));
el.classList.remove('pending');
var from = parseInt(el.textContent, 10);
if (isNaN(from)) from = 0;
if (reduce) { el.textContent = val; fit(); return; }
var t0 = performance.now();
(function step(t) {
var p = Math.min(1, (t - t0) / 600), e = 1 - Math.pow(1 - p, 3);
el.textContent = Math.round(from + (val - from) * e);
if (p < 1) requestAnimationFrame(step); else fit();
})(performance.now());
}
/* ========== 运行天数 ========== */
function runDays() {
if (CONFIG.daysMode === 'fixed') return parseInt(CONFIG.daysValue, 10) || 0;
var p = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(CONFIG.startDate);
if (!p) return null;
var d = new Date();
return Math.max(0, Math.round((Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) -
Date.UTC(+p[1], +p[2] - 1, +p[3])) / 86400000));
}
/* ========== WordPress 官方 REST(无需插件/密钥/PHP) ========== */
function restUrls(p) {
var b = CONFIG.base || '', i = p.indexOf('?');
var path = i < 0 ? p : p.slice(0, i), tail = i < 0 ? '' : '&' + p.slice(i + 1);
return [b + '/wp-json/wp/v2/' + p, b + '/?rest_route=/wp/v2/' + path + tail];
}
function firstResp(urls, ok) {
var i = 0;
return (function next() {
if (i >= urls.length) return Promise.resolve(null);
var u = urls[i++];
return fetch(u, { headers: { Accept: 'application/json' } })
.then(function (r) { return r.ok ? r : null; })
.catch(function () { return null; })
.then(function (r) { return (r && (!ok || ok(r))) ? r : next(); });
})();
}
function total(query) {
return firstResp(restUrls('posts?per_page=1&_fields=id&' + (query || '')),
function (r) { return r.headers.get('X-WP-Total') !== null; })
.then(function (r) { return r ? parseInt(r.headers.get('X-WP-Total'), 10) : null; });
}
function wpTime(d) {
return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 19);
}
function monday(d) {
var x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
return x;
}
function loadStats() {
var now = new Date();
Promise.all([
total('after=' + encodeURIComponent(wpTime(new Date(now.getFullYear(), now.getMonth(), now.getDate())))),
total('after=' + encodeURIComponent(wpTime(monday(now)))),
total(''),
firstResp(restUrls('users?per_page=1&_fields=id'),
function (r) { return r.headers.get('X-WP-Total') !== null; })
.then(function (r) { return r ? parseInt(r.headers.get('X-WP-Total'), 10) : null; })
]).then(function (r) {
setNum('today', r[0]);
setNum('week', r[1]);
setNum('posts', r[2]);
setNum('users', r[3]); /* 读不到就保持「—」,不填假数字 */
});
}
/* ========== 防溢出 + 深浅色 ========== */
function fit() {
Array.prototype.slice.call(root.querySelectorAll('.ws-num')).forEach(function (el) {
el.style.fontSize = '';
var box = el.closest ? el.closest('.ws-card') : null;
if (!box) { var p = el.parentNode;
while (p && p !== root) { if (p.className && String(p.className).indexOf('ws-card') > -1) { box = p; break; } p = p.parentNode; } }
if (!box || !box.clientWidth) return;
var avail = box.clientWidth - 10;
if (avail <= 0) return;
var base = parseFloat(getComputedStyle(el).fontSize) || 16;
var need = el.scrollWidth;
if (need > avail + 1 && need > 0)
el.style.fontSize = Math.max(11, base * avail / need * 0.97).toFixed(1) + 'px';
});
}
var mq = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
function applyDark() {
var h = document.documentElement, b = document.body;
var f = [h.className, b && b.className, h.getAttribute('data-theme'),
h.getAttribute('data-color-scheme'), b && b.getAttribute('data-theme')].join(' ');
var dark = /\bdark\b|dark-mode|theme-dark|night-mode|\bnight\b/i.test(f) ||
(!/\blight\b/i.test(f) && mq && mq.matches);
if (dark) root.setAttribute('data-dark', '1'); else root.removeAttribute('data-dark');
}
/* ========== 启动 ========== */
setNum('days', runDays());
loadStats();
fit();
applyDark();
if (mq) {
if (mq.addEventListener) mq.addEventListener('change', applyDark);
else if (mq.addListener) mq.addListener(applyDark);
}
var lastW = 0;
function onResize() {
var w = root.clientWidth;
if (!w || w === lastW) return;
lastW = w; fit();
}
if (window.ResizeObserver) new ResizeObserver(onResize).observe(root);
else window.addEventListener('resize', onResize);
})();
</script>| 位置 | 源码里的问题 | 改动 |
|---|---|---|
fit() 取父卡 |
el.closest ? el.closest('.ws-card') : null,环境没有 closest 时 box 恒为 null,量宽整段跳过 |
补一段沿 parentNode 找 .ws-card 的回退 |
| candy 的标签底色 | background:linear-gradient(135deg,var(--c),color-mix(...)) 整条依赖 color-mix(),不支持时整条作废,白字落在透明底上 |
前面加一条 background:var(--c),新浏览器由后者覆盖 |
setNum() 起始值 |
parseInt('—',10) 得到 NaN,isNaN(from) 成立就直写结果,默认配置下那段 600ms 缓动永远跑不到 |
把 NaN 折成 0,从「—」也能滚起来 |
紧凑款
同一段代码换一套 id 与容器名(hmM2 / wsM2),行高下限从 94px 收到 78px、网格 gap 7→5、图标 28→24,主色换成低饱和蓝绿。五格文字、CONFIG、REST 路径一字未动,同一页放两份也不会互相覆盖样式。
<!--
WP 侧边栏 · 中段(站点统计 2+3)· 独立一段
★ 单独粘进一个「外观 → 小工具 → 自定义 HTML」即可,不需要任何父容器 CSS。
★ 自适应:基础样式就是「窄侧边栏」紧凑态(上排 2 张大卡、下排 3 张小卡不变),
小工具变宽时按自身宽度自动放大(容器查询,按小工具宽度算,不按屏幕宽度)。
★ 与左/右段完全独立:CSS 前缀 hmM2、DOM id hmM2-*,同页不冲突。
★ 数字默认隐藏「—」:贴到博客后由 WordPress 官方 REST 读到真实值才显示;
接口读不到就一直保持「—」,不会出现 1404 / 2587 这类假数字。
★ 只改脚本顶部 CONFIG:
daysMode / daysValue 运行时间现在默认 fixed = 1 天;
想按建站日自动算就改回 'auto' 并填 startDate
reveal false = 直接显示 fallbacks 里的固定数字
base WP 装在子目录填 '/blog';跨域填完整域名
theme mist | candy | mono
★ 数据全部走 WP 自带 REST,无需插件/密钥/改 functions.php:
/wp/v2/posts 读今日更新、本周更新、文章数目;/wp/v2/users 读注册用户。
/wp-json/ 不通会自动改试 /?rest_route=/...
※ WP 对未登录访客只公开「有已发布文章的作者」,故该数是公开作者数。
★ 若编辑器过滤 <script>,把脚本内容用 WPCode / Insert Headers and Footers 插到页脚。
-->
<div id="hmM2">
<div class="stats-grid" id="hmM2-grid"></div>
</div>
<script>
(function () {
'use strict';
/* ========== 配置(★ 只改这一段) ========== */
var CONFIG = {
startDate: '2020-11-25', // 建站日 YYYY-MM-DD(daysMode='fixed' 时不生效)
daysMode: 'fixed', // 'fixed' 显示 daysValue | 'auto' 按建站日算
daysValue: 1, // ★ 当前默认 = 1 天
reveal: true, // true=先隐藏「—」,读到真实值才显示;false=显示下面固定值
fallbacks: { today: 0, week: 2, posts: 1404, users: 2587, days: 1 },
base: '', // 同域根目录留空;WP 在子目录填 '/blog';跨域填完整域名
theme: 'mist' // mist | candy | mono
};
var CARDS = [
{ key: 'today', icon: 'calendar', label: '今日更新', unit: '篇' },
{ key: 'week', icon: 'calendar7', label: '本周更新', unit: '篇' },
{ key: 'posts', icon: 'file', label: '文章数目', unit: '篇' },
{ key: 'users', icon: 'crown', label: '注册用户', unit: '位' },
{ key: 'days', icon: 'clock', label: '运行时间', unit: '天' }
];
var root = document.getElementById('hmM2');
var statsGrid = document.getElementById('hmM2-grid');
if (!root || !statsGrid) return;
root.setAttribute('data-theme', CONFIG.theme);
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
/* 样式:窄栏优先。基础即侧边栏紧凑态,宽了再按容器放大。 */
if (!document.getElementById('hmM2-css')) {
var css = `
#hmM2{container-type:inline-size;container-name:wsM2;box-sizing:border-box;
width:100%;margin:0;--card:#fff;--ink:#3f444d;--sub:#4a5059;
--shadow:0 2px 12px rgba(30,40,60,.05);
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif}
#hmM2,#hmM2 *{box-sizing:border-box}
#hmM2[data-theme="mist"]{--a1:#3d7ea6;--ab1:#e8f2f7;--a2:#3f9d78;--ab2:#e8f5ef;
--a3:#b9823a;--ab3:#f8f0e4;--a4:#6f76bd;--ab4:#eeeffa;--a5:#b56b78;--ab5:#f7ecef}
#hmM2[data-theme="candy"]{--a1:#d9668a;--ab1:#fdeef3;--a2:#d97a86;--ab2:#fdf0f0;
--a3:#dd8a5c;--ab3:#fdf1e9;--a4:#b174c0;--ab4:#f7edfa;--a5:#d9668a;--ab5:#fdeef3}
#hmM2[data-theme="mono"]{--a1:#5b6b82;--ab1:#eef1f5;--a2:#5b6b82;--ab2:#eef1f5;
--a3:#5b6b82;--ab3:#eef1f5;--a4:#5b6b82;--ab4:#eef1f5;--a5:#5b6b82;--ab5:#eef1f5}
#hmM2[data-dark="1"]{--card:#222834;--ink:#e9edf4;--sub:#c9d1de;
--shadow:0 2px 12px rgba(0,0,0,.28)}
/* 原版 2+3:上排 2 张 span 3、下排 3 张 span 2,行高按内容自然撑满 */
#hmM2 .stats-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:5px;
grid-template-rows:repeat(2,minmax(78px,auto))}
#hmM2 .ws-card{grid-column:span 3;min-width:0;background:var(--card);border-radius:13px;
padding:10px 4px 9px;box-shadow:var(--shadow);
display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;
transition:transform .2s,box-shadow .2s}
#hmM2 .ws-card:nth-child(3),#hmM2 .ws-card:nth-child(4),#hmM2 .ws-card:nth-child(5){grid-column:span 2}
#hmM2 .ws-card:nth-child(1){--c:var(--a1);--cb:var(--ab1)}
#hmM2 .ws-card:nth-child(2){--c:var(--a2);--cb:var(--ab2)}
#hmM2 .ws-card:nth-child(3){--c:var(--a3);--cb:var(--ab3)}
#hmM2 .ws-card:nth-child(4){--c:var(--a4);--cb:var(--ab4)}
#hmM2 .ws-card:nth-child(5){--c:var(--a5);--cb:var(--ab5)}
#hmM2 .ws-card:hover{transform:translateY(-3px);box-shadow:0 8px 22px rgba(30,40,60,.09)}
#hmM2 .ws-ico{width:24px;height:24px;flex:0 0 24px;border-radius:8px;background:var(--cb);
color:var(--c);display:grid;place-items:center;overflow:hidden}
#hmM2 .ws-ico svg{width:16px;height:16px;display:block}
#hmM2 .ws-ico img{width:100%;height:100%;object-fit:cover}
#hmM2 .ws-ico span{font-size:16px;line-height:1}
#hmM2 .ws-num{color:var(--ink);font-size:clamp(13px,4.4cqw,18px);font-weight:800;line-height:1.1;
letter-spacing:-.5px;white-space:nowrap;font-variant-numeric:tabular-nums;max-width:100%}
#hmM2 .ws-num [data-num].pending{color:var(--sub);opacity:.4;font-weight:600}
#hmM2 .ws-unit{font-size:.6em;font-weight:700;margin-left:3px}
#hmM2 .ws-tag{font-size:10px;font-weight:600;color:var(--c);background:var(--cb);
border-radius:999px;padding:3px 7px;white-space:nowrap;line-height:1.2}
#hmM2[data-theme="candy"] .ws-tag{color:#fff;
background:linear-gradient(135deg,var(--c),color-mix(in srgb,var(--c) 62%,#fff))}
#hmM2[data-dark="1"] .ws-ico,#hmM2[data-dark="1"] .ws-tag{background:rgba(255,255,255,.08)}
#hmM2[data-dark="1"] .ws-tag{color:color-mix(in srgb,var(--c) 72%,#fff)}
/* 侧边栏较宽:放大回原版比例 */
@container wsM2 (min-width:420px){
#hmM2 .stats-grid{gap:10px;grid-template-rows:repeat(2,minmax(106px,1fr))}
#hmM2 .ws-card{border-radius:14px;padding:14px 6px 12px;gap:8px}
#hmM2 .ws-ico{width:34px;height:34px;flex-basis:34px;border-radius:11px}
#hmM2 .ws-ico svg{width:19px;height:19px}
#hmM2 .ws-ico span{font-size:18px}
#hmM2 .ws-num{font-size:clamp(16px,4.8cqw,22px)}
#hmM2 .ws-tag{font-size:11px;padding:4px 10px}
}
/* 极窄侧边栏:再收一档,标签和数字都不会撑破卡片 */
@container wsM2 (max-width:230px){
#hmM2 .stats-grid{gap:5px}
#hmM2 .ws-card{padding:8px 3px 8px;gap:5px}
#hmM2 .ws-ico{width:24px;height:24px;flex-basis:24px}
#hmM2 .ws-ico svg{width:14px;height:14px}
#hmM2 .ws-tag{font-size:9px;padding:3px 5px}
}
@media (prefers-reduced-motion:reduce){
#hmM2 .ws-card{transition:none!important}#hmM2 .ws-card:hover{transform:none}}
`;
var st = document.createElement('style');
st.id = 'hmM2-css';
st.textContent = css;
(document.head || document.documentElement).appendChild(st);
}
/* ========== 图标 ========== */
var S = 'fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"';
var ICONS = {
calendar: '<svg viewBox="0 0 24 24" ' + S + '><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18M7 14h.01M12 14h.01M17 14h.01M7 18h.01M12 18h.01"/></svg>',
calendar7: '<svg viewBox="0 0 24 24" ' + S + '><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18"/><text x="12" y="18.2" text-anchor="middle" font-size="9" font-weight="700" fill="currentColor" stroke="none">7</text></svg>',
file: '<svg viewBox="0 0 24 24" ' + S + '><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8M8 17h5"/></svg>',
crown: '<svg viewBox="0 0 24 24" ' + S + '><path d="M3 8l4 4 5-7 5 7 4-4-2 11H5z"/><path d="M5 20h14"/></svg>',
clock: '<svg viewBox="0 0 24 24" ' + S + '><path d="M3.5 12a8.5 8.5 0 1 0 2.6-6.1M3 4v4h4"/><path d="M12 7.5V12l3 2"/></svg>'
};
function esc(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
});
}
function iconHTML(v) {
if (ICONS[v]) return ICONS[v];
if (/^<svg[\s>]/i.test(v)) return v;
if (/^(https?:\/\/|\/|\.\/)/i.test(v) || /\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(v))
return '<img src="' + esc(v) + '" alt="">';
return '<span>' + esc(v || '★') + '</span>';
}
CARDS.forEach(function (c) {
var el = document.createElement('div');
el.className = 'ws-card';
var init = CONFIG.reveal ? '—' : CONFIG.fallbacks[c.key];
el.innerHTML = '<div class="ws-ico">' + iconHTML(c.icon) + '</div>' +
'<div class="ws-num"><span data-num="' + c.key + '"' +
(CONFIG.reveal ? ' class="pending"' : '') + '>' + init + '</span>' +
'<span class="ws-unit">' + esc(c.unit) + '</span></div>' +
'<div class="ws-tag">' + esc(c.label) + '</div>';
statsGrid.appendChild(el);
});
/* ========== 数字:只有拿到真实值才现身 ========== */
function setNum(key, val) {
if (val === null || val === undefined || isNaN(val)) return;
var el = root.querySelector('[data-num="' + key + '"]');
if (!el) return;
val = Math.max(0, Math.round(val));
el.classList.remove('pending');
var from = parseInt(el.textContent, 10);
if (isNaN(from) || reduce) { el.textContent = val; fit(); return; }
var t0 = performance.now();
(function step(t) {
var p = Math.min(1, (t - t0) / 600), e = 1 - Math.pow(1 - p, 3);
el.textContent = Math.round(from + (val - from) * e);
if (p < 1) requestAnimationFrame(step); else fit();
})(performance.now());
}
/* ========== 运行天数 ========== */
function runDays() {
if (CONFIG.daysMode === 'fixed') return parseInt(CONFIG.daysValue, 10) || 0;
var p = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(CONFIG.startDate);
if (!p) return null;
var d = new Date();
return Math.max(0, Math.round((Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) -
Date.UTC(+p[1], +p[2] - 1, +p[3])) / 86400000));
}
/* ========== WordPress 官方 REST(无需插件/密钥/PHP) ========== */
function restUrls(p) {
var b = CONFIG.base || '', i = p.indexOf('?');
var path = i < 0 ? p : p.slice(0, i), tail = i < 0 ? '' : '&' + p.slice(i + 1);
return [b + '/wp-json/wp/v2/' + p, b + '/?rest_route=/wp/v2/' + path + tail];
}
function firstResp(urls, ok) {
var i = 0;
return (function next() {
if (i >= urls.length) return Promise.resolve(null);
var u = urls[i++];
return fetch(u, { headers: { Accept: 'application/json' } })
.then(function (r) { return r.ok ? r : null; })
.catch(function () { return null; })
.then(function (r) { return (r && (!ok || ok(r))) ? r : next(); });
})();
}
function total(query) {
return firstResp(restUrls('posts?per_page=1&_fields=id&' + (query || '')),
function (r) { return r.headers.get('X-WP-Total') !== null; })
.then(function (r) { return r ? parseInt(r.headers.get('X-WP-Total'), 10) : null; });
}
function wpTime(d) {
return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 19);
}
function monday(d) {
var x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
return x;
}
function loadStats() {
var now = new Date();
Promise.all([
total('after=' + encodeURIComponent(wpTime(new Date(now.getFullYear(), now.getMonth(), now.getDate())))),
total('after=' + encodeURIComponent(wpTime(monday(now)))),
total(''),
firstResp(restUrls('users?per_page=1&_fields=id'),
function (r) { return r.headers.get('X-WP-Total') !== null; })
.then(function (r) { return r ? parseInt(r.headers.get('X-WP-Total'), 10) : null; })
]).then(function (r) {
setNum('today', r[0]);
setNum('week', r[1]);
setNum('posts', r[2]);
setNum('users', r[3]); /* 读不到就保持「—」,不填假数字 */
});
}
/* ========== 防溢出 + 深浅色 ========== */
function fit() {
Array.prototype.slice.call(root.querySelectorAll('.ws-num')).forEach(function (el) {
el.style.fontSize = '';
var box = el.closest ? el.closest('.ws-card') : null;
if (!box || !box.clientWidth) return;
var avail = box.clientWidth - 10;
if (avail <= 0) return;
var base = parseFloat(getComputedStyle(el).fontSize) || 16;
var need = el.scrollWidth;
if (need > avail + 1 && need > 0)
el.style.fontSize = Math.max(11, base * avail / need * 0.97).toFixed(1) + 'px';
});
}
var mq = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
function applyDark() {
var h = document.documentElement, b = document.body;
var f = [h.className, b && b.className, h.getAttribute('data-theme'),
h.getAttribute('data-color-scheme'), b && b.getAttribute('data-theme')].join(' ');
var dark = /\bdark\b|dark-mode|theme-dark|night-mode|\bnight\b/i.test(f) ||
(!/\blight\b/i.test(f) && mq && mq.matches);
if (dark) root.setAttribute('data-dark', '1'); else root.removeAttribute('data-dark');
}
/* ========== 启动 ========== */
setNum('days', runDays());
loadStats();
fit();
applyDark();
if (mq) {
if (mq.addEventListener) mq.addEventListener('change', applyDark);
else if (mq.addListener) mq.addListener(applyDark);
}
var lastW = 0;
function onResize() {
var w = root.clientWidth;
if (!w || w === lastW) return;
lastW = w; fit();
}
if (window.ResizeObserver) new ResizeObserver(onResize).observe(root);
else window.addEventListener('resize', onResize);
})();
</script>深色款
换成 hmM3 / wsM3,把基础 --card / --ink / --sub 直接写成深色值,--a1~--a5 换成亮一档的紫蓝。applyDark() 没动:它把 documentElement.className、body.className、data-theme、data-color-scheme 拼起来做正则匹配,命中 \bdark\b|dark-mode|theme-dark|night-mode|\bnight\b,或系统偏好深色且类名里没有 light 时,给 root 加 data-dark="1",只换四个变量。
<!--
WP 侧边栏 · 中段(站点统计 2+3)· 独立一段
★ 单独粘进一个「外观 → 小工具 → 自定义 HTML」即可,不需要任何父容器 CSS。
★ 自适应:基础样式就是「窄侧边栏」紧凑态(上排 2 张大卡、下排 3 张小卡不变),
小工具变宽时按自身宽度自动放大(容器查询,按小工具宽度算,不按屏幕宽度)。
★ 与左/右段完全独立:CSS 前缀 hmM3、DOM id hmM3-*,同页不冲突。
★ 数字默认隐藏「—」:贴到博客后由 WordPress 官方 REST 读到真实值才显示;
接口读不到就一直保持「—」,不会出现 1404 / 2587 这类假数字。
★ 只改脚本顶部 CONFIG:
daysMode / daysValue 运行时间现在默认 fixed = 1 天;
想按建站日自动算就改回 'auto' 并填 startDate
reveal false = 直接显示 fallbacks 里的固定数字
base WP 装在子目录填 '/blog';跨域填完整域名
theme mist | candy | mono
★ 数据全部走 WP 自带 REST,无需插件/密钥/改 functions.php:
/wp/v2/posts 读今日更新、本周更新、文章数目;/wp/v2/users 读注册用户。
/wp-json/ 不通会自动改试 /?rest_route=/...
※ WP 对未登录访客只公开「有已发布文章的作者」,故该数是公开作者数。
★ 若编辑器过滤 <script>,把脚本内容用 WPCode / Insert Headers and Footers 插到页脚。
-->
<div id="hmM3">
<div class="stats-grid" id="hmM3-grid"></div>
</div>
<script>
(function () {
'use strict';
/* ========== 配置(★ 只改这一段) ========== */
var CONFIG = {
startDate: '2020-11-25', // 建站日 YYYY-MM-DD(daysMode='fixed' 时不生效)
daysMode: 'fixed', // 'fixed' 显示 daysValue | 'auto' 按建站日算
daysValue: 1, // ★ 当前默认 = 1 天
reveal: true, // true=先隐藏「—」,读到真实值才显示;false=显示下面固定值
fallbacks: { today: 0, week: 2, posts: 1404, users: 2587, days: 1 },
base: '', // 同域根目录留空;WP 在子目录填 '/blog';跨域填完整域名
theme: 'mist' // mist | candy | mono
};
var CARDS = [
{ key: 'today', icon: 'calendar', label: '今日更新', unit: '篇' },
{ key: 'week', icon: 'calendar7', label: '本周更新', unit: '篇' },
{ key: 'posts', icon: 'file', label: '文章数目', unit: '篇' },
{ key: 'users', icon: 'crown', label: '注册用户', unit: '位' },
{ key: 'days', icon: 'clock', label: '运行时间', unit: '天' }
];
var root = document.getElementById('hmM3');
var statsGrid = document.getElementById('hmM3-grid');
if (!root || !statsGrid) return;
root.setAttribute('data-theme', CONFIG.theme);
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
/* 样式:窄栏优先。基础即侧边栏紧凑态,宽了再按容器放大。 */
if (!document.getElementById('hmM3-css')) {
var css = `
#hmM3{container-type:inline-size;container-name:wsM3;box-sizing:border-box;
width:100%;margin:0;--card:#222834;--ink:#e9edf4;--sub:#c9d1de;
--shadow:0 2px 12px rgba(30,40,60,.05);
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif}
#hmM3,#hmM3 *{box-sizing:border-box}
#hmM3[data-theme="mist"]{--a1:#7aa2ff;--ab1:#2b3650;--a2:#5cc9a7;--ab2:#263f3a;
--a3:#e0a45e;--ab3:#3b3327;--a4:#ad94ee;--ab4:#332c4a;--a5:#e28790;--ab5:#3b2a30}
#hmM3[data-theme="candy"]{--a1:#d9668a;--ab1:#fdeef3;--a2:#d97a86;--ab2:#fdf0f0;
--a3:#dd8a5c;--ab3:#fdf1e9;--a4:#b174c0;--ab4:#f7edfa;--a5:#d9668a;--ab5:#fdeef3}
#hmM3[data-theme="mono"]{--a1:#5b6b82;--ab1:#eef1f5;--a2:#5b6b82;--ab2:#eef1f5;
--a3:#5b6b82;--ab3:#eef1f5;--a4:#5b6b82;--ab4:#eef1f5;--a5:#5b6b82;--ab5:#eef1f5}
#hmM3[data-dark="1"]{--card:#222834;--ink:#e9edf4;--sub:#c9d1de;
--shadow:0 2px 12px rgba(0,0,0,.28)}
/* 原版 2+3:上排 2 张 span 3、下排 3 张 span 2,行高按内容自然撑满 */
#hmM3 .stats-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:7px;
grid-template-rows:repeat(2,minmax(94px,auto))}
#hmM3 .ws-card{grid-column:span 3;min-width:0;background:var(--card);border-radius:13px;
padding:10px 4px 9px;box-shadow:var(--shadow);
display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;
transition:transform .2s,box-shadow .2s}
#hmM3 .ws-card:nth-child(3),#hmM3 .ws-card:nth-child(4),#hmM3 .ws-card:nth-child(5){grid-column:span 2}
#hmM3 .ws-card:nth-child(1){--c:var(--a1);--cb:var(--ab1)}
#hmM3 .ws-card:nth-child(2){--c:var(--a2);--cb:var(--ab2)}
#hmM3 .ws-card:nth-child(3){--c:var(--a3);--cb:var(--ab3)}
#hmM3 .ws-card:nth-child(4){--c:var(--a4);--cb:var(--ab4)}
#hmM3 .ws-card:nth-child(5){--c:var(--a5);--cb:var(--ab5)}
#hmM3 .ws-card:hover{transform:translateY(-3px);box-shadow:0 8px 22px rgba(30,40,60,.09)}
#hmM3 .ws-ico{width:28px;height:28px;flex:0 0 28px;border-radius:9px;background:var(--cb);
color:var(--c);display:grid;place-items:center;overflow:hidden}
#hmM3 .ws-ico svg{width:16px;height:16px;display:block}
#hmM3 .ws-ico img{width:100%;height:100%;object-fit:cover}
#hmM3 .ws-ico span{font-size:16px;line-height:1}
#hmM3 .ws-num{color:var(--ink);font-size:clamp(13px,4.4cqw,18px);font-weight:800;line-height:1.1;
letter-spacing:-.5px;white-space:nowrap;font-variant-numeric:tabular-nums;max-width:100%}
#hmM3 .ws-num [data-num].pending{color:var(--sub);opacity:.4;font-weight:600}
#hmM3 .ws-unit{font-size:.6em;font-weight:700;margin-left:3px}
#hmM3 .ws-tag{font-size:10px;font-weight:600;color:var(--c);background:var(--cb);
border-radius:999px;padding:3px 7px;white-space:nowrap;line-height:1.2}
#hmM3[data-theme="candy"] .ws-tag{color:#fff;
background:linear-gradient(135deg,var(--c),color-mix(in srgb,var(--c) 62%,#fff))}
#hmM3[data-dark="1"] .ws-ico,#hmM3[data-dark="1"] .ws-tag{background:rgba(255,255,255,.08)}
#hmM3[data-dark="1"] .ws-tag{color:color-mix(in srgb,var(--c) 72%,#fff)}
/* 侧边栏较宽:放大回原版比例 */
@container wsM3 (min-width:420px){
#hmM3 .stats-grid{gap:10px;grid-template-rows:repeat(2,minmax(106px,1fr))}
#hmM3 .ws-card{border-radius:14px;padding:14px 6px 12px;gap:8px}
#hmM3 .ws-ico{width:34px;height:34px;flex-basis:34px;border-radius:11px}
#hmM3 .ws-ico svg{width:19px;height:19px}
#hmM3 .ws-ico span{font-size:18px}
#hmM3 .ws-num{font-size:clamp(16px,4.8cqw,22px)}
#hmM3 .ws-tag{font-size:11px;padding:4px 10px}
}
/* 极窄侧边栏:再收一档,标签和数字都不会撑破卡片 */
@container wsM3 (max-width:230px){
#hmM3 .stats-grid{gap:5px}
#hmM3 .ws-card{padding:8px 3px 8px;gap:5px}
#hmM3 .ws-ico{width:24px;height:24px;flex-basis:24px}
#hmM3 .ws-ico svg{width:14px;height:14px}
#hmM3 .ws-tag{font-size:9px;padding:3px 5px}
}
@media (prefers-reduced-motion:reduce){
#hmM3 .ws-card{transition:none!important}#hmM3 .ws-card:hover{transform:none}}
`;
var st = document.createElement('style');
st.id = 'hmM3-css';
st.textContent = css;
(document.head || document.documentElement).appendChild(st);
}
/* ========== 图标 ========== */
var S = 'fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"';
var ICONS = {
calendar: '<svg viewBox="0 0 24 24" ' + S + '><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18M7 14h.01M12 14h.01M17 14h.01M7 18h.01M12 18h.01"/></svg>',
calendar7: '<svg viewBox="0 0 24 24" ' + S + '><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 10h18"/><text x="12" y="18.2" text-anchor="middle" font-size="9" font-weight="700" fill="currentColor" stroke="none">7</text></svg>',
file: '<svg viewBox="0 0 24 24" ' + S + '><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8M8 17h5"/></svg>',
crown: '<svg viewBox="0 0 24 24" ' + S + '><path d="M3 8l4 4 5-7 5 7 4-4-2 11H5z"/><path d="M5 20h14"/></svg>',
clock: '<svg viewBox="0 0 24 24" ' + S + '><path d="M3.5 12a8.5 8.5 0 1 0 2.6-6.1M3 4v4h4"/><path d="M12 7.5V12l3 2"/></svg>'
};
function esc(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
});
}
function iconHTML(v) {
if (ICONS[v]) return ICONS[v];
if (/^<svg[\s>]/i.test(v)) return v;
if (/^(https?:\/\/|\/|\.\/)/i.test(v) || /\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(v))
return '<img src="' + esc(v) + '" alt="">';
return '<span>' + esc(v || '★') + '</span>';
}
CARDS.forEach(function (c) {
var el = document.createElement('div');
el.className = 'ws-card';
var init = CONFIG.reveal ? '—' : CONFIG.fallbacks[c.key];
el.innerHTML = '<div class="ws-ico">' + iconHTML(c.icon) + '</div>' +
'<div class="ws-num"><span data-num="' + c.key + '"' +
(CONFIG.reveal ? ' class="pending"' : '') + '>' + init + '</span>' +
'<span class="ws-unit">' + esc(c.unit) + '</span></div>' +
'<div class="ws-tag">' + esc(c.label) + '</div>';
statsGrid.appendChild(el);
});
/* ========== 数字:只有拿到真实值才现身 ========== */
function setNum(key, val) {
if (val === null || val === undefined || isNaN(val)) return;
var el = root.querySelector('[data-num="' + key + '"]');
if (!el) return;
val = Math.max(0, Math.round(val));
el.classList.remove('pending');
var from = parseInt(el.textContent, 10);
if (isNaN(from) || reduce) { el.textContent = val; fit(); return; }
var t0 = performance.now();
(function step(t) {
var p = Math.min(1, (t - t0) / 600), e = 1 - Math.pow(1 - p, 3);
el.textContent = Math.round(from + (val - from) * e);
if (p < 1) requestAnimationFrame(step); else fit();
})(performance.now());
}
/* ========== 运行天数 ========== */
function runDays() {
if (CONFIG.daysMode === 'fixed') return parseInt(CONFIG.daysValue, 10) || 0;
var p = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(CONFIG.startDate);
if (!p) return null;
var d = new Date();
return Math.max(0, Math.round((Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) -
Date.UTC(+p[1], +p[2] - 1, +p[3])) / 86400000));
}
/* ========== WordPress 官方 REST(无需插件/密钥/PHP) ========== */
function restUrls(p) {
var b = CONFIG.base || '', i = p.indexOf('?');
var path = i < 0 ? p : p.slice(0, i), tail = i < 0 ? '' : '&' + p.slice(i + 1);
return [b + '/wp-json/wp/v2/' + p, b + '/?rest_route=/wp/v2/' + path + tail];
}
function firstResp(urls, ok) {
var i = 0;
return (function next() {
if (i >= urls.length) return Promise.resolve(null);
var u = urls[i++];
return fetch(u, { headers: { Accept: 'application/json' } })
.then(function (r) { return r.ok ? r : null; })
.catch(function () { return null; })
.then(function (r) { return (r && (!ok || ok(r))) ? r : next(); });
})();
}
function total(query) {
return firstResp(restUrls('posts?per_page=1&_fields=id&' + (query || '')),
function (r) { return r.headers.get('X-WP-Total') !== null; })
.then(function (r) { return r ? parseInt(r.headers.get('X-WP-Total'), 10) : null; });
}
function wpTime(d) {
return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 19);
}
function monday(d) {
var x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
return x;
}
function loadStats() {
var now = new Date();
Promise.all([
total('after=' + encodeURIComponent(wpTime(new Date(now.getFullYear(), now.getMonth(), now.getDate())))),
total('after=' + encodeURIComponent(wpTime(monday(now)))),
total(''),
firstResp(restUrls('users?per_page=1&_fields=id'),
function (r) { return r.headers.get('X-WP-Total') !== null; })
.then(function (r) { return r ? parseInt(r.headers.get('X-WP-Total'), 10) : null; })
]).then(function (r) {
setNum('today', r[0]);
setNum('week', r[1]);
setNum('posts', r[2]);
setNum('users', r[3]); /* 读不到就保持「—」,不填假数字 */
});
}
/* ========== 防溢出 + 深浅色 ========== */
function fit() {
Array.prototype.slice.call(root.querySelectorAll('.ws-num')).forEach(function (el) {
el.style.fontSize = '';
var box = el.closest ? el.closest('.ws-card') : null;
if (!box || !box.clientWidth) return;
var avail = box.clientWidth - 10;
if (avail <= 0) return;
var base = parseFloat(getComputedStyle(el).fontSize) || 16;
var need = el.scrollWidth;
if (need > avail + 1 && need > 0)
el.style.fontSize = Math.max(11, base * avail / need * 0.97).toFixed(1) + 'px';
});
}
var mq = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;
function applyDark() {
var h = document.documentElement, b = document.body;
var f = [h.className, b && b.className, h.getAttribute('data-theme'),
h.getAttribute('data-color-scheme'), b && b.getAttribute('data-theme')].join(' ');
var dark = /\bdark\b|dark-mode|theme-dark|night-mode|\bnight\b/i.test(f) ||
(!/\blight\b/i.test(f) && mq && mq.matches);
if (dark) root.setAttribute('data-dark', '1'); else root.removeAttribute('data-dark');
}
/* ========== 启动 ========== */
setNum('days', runDays());
loadStats();
fit();
applyDark();
if (mq) {
if (mq.addEventListener) mq.addEventListener('change', applyDark);
else if (mq.addListener) mq.addListener(applyDark);
}
var lastW = 0;
function onResize() {
var w = root.clientWidth;
if (!w || w === lastW) return;
lastW = w; fit();
}
if (window.ResizeObserver) new ResizeObserver(onResize).observe(root);
else window.addEventListener('resize', onResize);
})();
</script>为什么都收在 #hmM 下面
样式表里每条选择器都以 #hmM 开头,DOM 里的 id 也是 hmM- 打头。这不是多余的:脚本注入的是全局样式表,若写成 .ws-card{...} 这样的裸类名,会一并命中主题里同名的元素。全部收进 #hmM 后,卡片、图标、圆标签只在自己的容器里生效;hmM-css 那个判重也是同理,同页贴两次不会插两份样式。两个变体各换一套前缀,就是为了能并排预览而不串台。
注意这几点
- DOM 和样式都依赖脚本执行:
<script>没跑起来,页面只剩两个空 div,连卡片带样式一起没有。 - 容器查询没有降级:
container-type:inline-size不被支持时两档@container都不命中,只剩基础态,这段没写@supports not回退。 color-mix()只在 candy 用到:旧浏览器上那条渐变会失效,标签底色退化。fit()有个下限:它量scrollWidth与卡片clientWidth-10,超了按base*avail/need*0.97缩,但不会小于 11px;数字特别长时仍可能贴边。- 内置图标没写 xmlns:
ICONS里 5 段 SVG 靠innerHTML由 HTML 解析器补命名空间,单独存成.svg文件打开是显示不出来的。 - 「今日」按站点本地时区算:
wpTime()用getTimezoneOffset()折算后toISOString().slice(0,19),monday()用(getDay()+6)%7回退到周一。 - 四个数字都只取响应头:
users那格同样读X-WP-Total,请求里带per_page=1&_fields=id,不拉列表。
怎么用
整段贴进 WordPress 的「自定义 HTML」区块或外观里的小工具;经典编辑器用「文本」模式,别切回可视化再保存。要换数据来源,改 CONFIG 里的 daysMode / daysValue / reveal / base / theme 即可,base 留空表示同域根目录。theme 三套只改 --a1~--a5 和 --ab1~--ab5 这十组变量,布局与取数不受影响。
示例代码里的链接统一指向 维形筑网 www.wxzcw.com。
兼容性
fetch、Promise.all、requestAnimationFrame、classList、ResizeObserver 在 Chrome / Edge / Firefox / Safari 新版都有;ResizeObserver 缺失时脚本回退到 window.addEventListener('resize', onResize),matchMedia 每处都做了存在判断。@container 需要较新的浏览器,color-mix() 更晚一些,这两处正是修复版补兜底的地方。
代码仅供学习交流,禁止商用。更多网站美化代码,前往 维形筑网 www.wxzcw.com。
作者:Flechazo
如若转载,请注明出处:维形筑网 https://wxzcw.com