You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在含MathJax的HTML页面中实现LaTeX式定理引用功能?

实现MathJax网页中的LaTeX风格定理引用

嗨,我来帮你搞定这个定理引用的需求!结合你已经有的自动编号CSS,咱们可以通过HTML结构调整+JavaScript辅助,实现和LaTeX几乎一致的定理引用效果,包括自动同步编号和点击跳转功能。

第一步:完善CSS计数器体系

首先把你现有的CSS补全,确保章节和定理的计数器能正确嵌套递增:

/* 初始化章节计数器,假设你用自定义类划分章节 */
body {
  counter-reset: chap 0; /* 章节计数器初始化为0 */
}

.chapter {
  counter-reset: sect 0; /* 每章重置小节计数器 */
  counter-increment: chap; /* 章节编号递增 */
}

.section {
  counter-reset: thm 0; /* 每小节重置定理计数器 */
  counter-increment: sect; /* 小节编号递增 */
}

/* 定理样式+自动编号 */
.theorem {
  counter-increment: thm; /* 每个定理编号递增 */
  margin: 1em 0;
  padding: 0.5em;
  border-left: 3px solid #2c3e50;
  background-color: #f8f9fa;
}

.theorem:before {
  font-style: normal;
  font-weight: bold;
  content: "Theorem " counter(chap)"."counter(sect)"."counter(thm)" ";
  color: #2c3e50;
}

第二步:HTML结构规范

每个定理需要添加唯一的id(对应LaTeX的\label),引用部分用自定义标记元素来占位:

<!-- 示例章节结构 -->
<div class="chapter">
  <h1>第一章 代数基础</h1>
  <div class="section">
    <h2>1.1 加法交换律</h2>
    
    <!-- 定理块,id对应LaTeX的label名 -->
    <div class="theorem" id="thm:commute">
      \(a + b = b + a\)
    </div>

    <!-- 引用定理的部分 -->
    <p>根据定理<span class="ref" data-ref="thm:commute"></span>,\(2 + 3 = 3 + 2\) 成立。</p>
  </div>
</div>

第三步:JavaScript实现引用同步与跳转

这段脚本会自动填充引用的编号,支持点击跳转到对应定理,还能兼容MathJax的渲染时机:

// 等待MathJax渲染完成后执行(适配MathJax v3)
document.addEventListener('DOMContentLoaded', function() {
  if (window.MathJax) {
    MathJax.startup.promise.then(updateTheoremRefs);
  } else {
    updateTheoremRefs(); // 无MathJax时直接执行
  }
});

function updateTheoremRefs() {
  const refs = document.querySelectorAll('.ref');
  
  refs.forEach(ref => {
    const targetId = ref.getAttribute('data-ref');
    const theorem = document.getElementById(targetId);
    
    if (!theorem) return;
    
    // 提取定理的编号(从:before伪元素的内容中解析)
    const computedStyle = window.getComputedStyle(theorem, ':before');
    const fullContent = computedStyle.content.replace(/"/g, ''); // 去掉浏览器自动添加的引号
    const theoremNumber = fullContent.replace('Theorem ', '');
    
    // 填充引用文本
    ref.textContent = `(${theoremNumber})`;
    
    // 添加点击跳转交互
    ref.style.cursor = 'pointer';
    ref.style.color = '#2980b9';
    ref.addEventListener('click', () => {
      theorem.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
  });
}

效果说明

  • 定理会自动生成章节.小节.序号的层级编号,和LaTeX的编号逻辑完全对齐
  • 引用位置会自动同步定理的最新编号,不需要手动修改
  • 点击引用文本会平滑跳转到对应的定理区块
  • 完全兼容MathJax的公式渲染流程,不会出现编号错位的问题

内容的提问来源于stack exchange,提问作者Valerio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:32:01