math-renderer.blade.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. @once
  2. @push('styles')
  3. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
  4. @endpush
  5. @push('scripts')
  6. <script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
  7. <script>
  8. document.addEventListener('DOMContentLoaded', function() {
  9. console.log('数学渲染器加载');
  10. function renderMath() {
  11. // 查找所有包含 $$ 的元素
  12. const elements = document.querySelectorAll('*');
  13. elements.forEach(element => {
  14. if (element.children.length === 0) { // 只处理叶子节点
  15. const text = element.textContent;
  16. if (text && text.includes('$$')) {
  17. try {
  18. const newHtml = text.replace(/\$\$([^$]+)\$\$/g, (match, formula) => {
  19. return katex.renderToString(formula.trim(), {
  20. throwOnError: false,
  21. displayMode: true
  22. });
  23. });
  24. if (newHtml !== text) {
  25. element.innerHTML = newHtml;
  26. }
  27. } catch (e) {
  28. console.warn('数学公式渲染失败:', e);
  29. }
  30. }
  31. }
  32. });
  33. }
  34. // 页面加载后渲染
  35. setTimeout(renderMath, 500);
  36. // Livewire 更新后重新渲染
  37. if (window.Livewire) {
  38. window.Livewire.on('updated', () => {
  39. setTimeout(renderMath, 100);
  40. });
  41. }
  42. // 添加手动渲染函数
  43. window.renderMath = renderMath;
  44. });
  45. </script>
  46. @endpush
  47. @endonce