为Stacks Editor添加LaTeX数学公式支持的实现方法
为Stacks Editor添加LaTeX数学公式支持
要让Stacks Editor支持输入$\frac{1}{2}$这类LaTeX数学公式并实时渲染,你需要引入公式渲染库并配置编辑器的渲染钩子,具体步骤如下:
1. 引入MathJax库及配置
在HTML的<head>区域,添加MathJax的CDN脚本和配置,让它识别行内($...$)和块级($$...$$)公式标记:
<!-- MathJax配置 --> <script> MathJax = { tex: { inlineMath: [['$', '$'], ['\\(', '\\)']] }, svg: { fontCache: 'global' } }; </script> <!-- 加载MathJax核心库 --> <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
2. 配置Stacks Editor的渲染钩子
修改编辑器初始化代码,添加postRender钩子,确保每次内容渲染完成后触发MathJax重新排版公式:
new window.stacksEditor.StacksEditor( document.querySelector("#editor-container"), "*Your* **markdown** here\n\n试试行内公式:$\\frac{1}{2}$\n\n或者块级公式:$$\\sum_{i=1}^n i = \\frac{n(n+1)}{2}$$", { postRender: () => { if (window.MathJax) { MathJax.typesetPromise(); } } } );
完整示例代码
<!DOCTYPE html> <html> <head> <title>Markdown Editor with LaTeX Support</title> <!--include Stacks --> <link rel="stylesheet" href="./node_modules/@stackoverflow/stacks/dist/css/stacks.css" /> <!-- include the bundled styles --> <link rel="stylesheet" href="./node_modules/@stackoverflow/stacks-editor/dist/styles.css" /> <!-- highlight.js --> <script src="//unpkg.com/@highlightjs/cdn-assets@latest/highlight.min.js"></script> <!--include Stacks --> <script src="./node_modules/@stackoverflow/stacks/dist/js/stacks.min.js"></script> <!-- include the bundle --> <script src="./node_modules/@stackoverflow/stacks-editor/dist/app.bundle.js"></script> <!-- MathJax配置与引入 --> <script> MathJax = { tex: { inlineMath: [['$', '$'], ['\\(', '\\)']] }, svg: { fontCache: 'global' } }; </script> <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> </head> <body> <div style="margin:20px; width: 800px;"> <div id="editor-container"></div> <!-- initialize the editor --> <script> new window.stacksEditor.StacksEditor( document.querySelector("#editor-container"), "*Your* **markdown** here\n\n试试行内公式:$\\frac{1}{2}$\n\n或者块级公式:$$\\sum_{i=1}^n i = \\frac{n(n+1)}{2}$$", { postRender: () => { if (window.MathJax) { MathJax.typesetPromise(); } } } ); </script> </div> </body> </html>
说明
- 行内公式用
$...$包裹,块级公式用$$...$$包裹,输入后预览区会自动渲染成对应的数学符号。 postRender钩子会在编辑器每次更新内容(输入、切换编辑/预览模式)后触发,确保新输入的公式能被及时渲染。
内容的提问来源于stack exchange,提问作者Kernier
相关产品推荐
相关产品推荐

