目录高亮的思路
监听正文标题的可见状态,反向高亮对应的目录项。
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setActive(entry.target.id);
}
});
}, { rootMargin: '-80px 0px -70% 0px' });
document.querySelectorAll('article h2, article h3').forEach((h) => {
observer.observe(h);
});
图片查看器
原生 <dialog> 已经足够好用:
const dlg = document.querySelector('#lightbox');
document.querySelectorAll('.post-content img').forEach((img) => {
img.addEventListener('click', () => {
dlg.querySelector('img').src = img.src;
dlg.showModal();
});
});
深色模式切换
const root = document.documentElement;
root.dataset.theme = localStorage.getItem('theme') || 'light';
| 能力 | 方案 | 体积 |
|---|---|---|
| 目录高亮 | IntersectionObserver | 1KB |
| 图片查看 | dialog | 2KB |
| 主题切换 | CSS 变量 | 0.5KB |
结语
把浏览器自带的能力用足,往往比引入一个库更划算。
评论 0