test-math-debug.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // 简化的数学公式渲染调试脚本
  2. (function() {
  3. 'use strict';
  4. console.log('[Debug] Script loaded');
  5. // 等待页面加载完成
  6. function init() {
  7. console.log('[Debug] DOMContentLoaded fired');
  8. // 检查 KaTeX 是否存在
  9. if (typeof window.katex === 'undefined') {
  10. console.error('[Debug] KaTeX is not loaded!');
  11. return;
  12. }
  13. console.log('[Debug] KaTeX is loaded:', window.katex);
  14. // 查找所有 math-render 元素
  15. const elements = document.querySelectorAll('.math-render');
  16. console.log('[Debug] Found', elements.length, 'math-render elements');
  17. elements.forEach((el, index) => {
  18. console.log(`[Debug] Element ${index}:`, el);
  19. renderElement(el);
  20. });
  21. }
  22. function renderElement(element) {
  23. if (!element) return;
  24. // 避免重复渲染
  25. if (element.dataset.rendered === 'true') {
  26. console.log('[Debug] Already rendered:', element);
  27. return;
  28. }
  29. const content = element.dataset.mathContent || element.textContent;
  30. console.log('[Debug] Content to render:', content);
  31. if (!content) {
  32. console.warn('[Debug] No content found');
  33. return;
  34. }
  35. try {
  36. let html = content;
  37. // 渲染 $$...$$ 块级公式
  38. html = html.replace(/\$\$([\s\S]*?)\$\$/g, (match, formula) => {
  39. try {
  40. return window.katex.renderToString(formula.trim(), {
  41. throwOnError: false,
  42. displayMode: true
  43. });
  44. } catch (e) {
  45. console.warn('KaTeX block render error:', e);
  46. return match;
  47. }
  48. });
  49. // 渲染 $...$ 行内公式
  50. html = html.replace(/\$(.*?)\$/g, (match, formula) => {
  51. try {
  52. console.log('[Debug] Rendering inline formula:', formula);
  53. return window.katex.renderToString(formula, {
  54. throwOnError: false,
  55. displayMode: false
  56. });
  57. } catch (e) {
  58. console.warn('KaTeX inline render error:', e);
  59. return match;
  60. }
  61. });
  62. console.log('[Debug] Rendered HTML:', html);
  63. element.innerHTML = html;
  64. element.dataset.rendered = 'true';
  65. console.log('[Debug] Rendered successfully');
  66. } catch (e) {
  67. console.error('[Debug] Render error:', e);
  68. }
  69. }
  70. // 监听 DOMContentLoaded
  71. if (document.readyState === 'loading') {
  72. document.addEventListener('DOMContentLoaded', init);
  73. } else {
  74. init();
  75. }
  76. })();