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

求可在Apache2本地服务器运行的Dynamic MathJax简易index.php示例

可运行的动态MathJax本地示例(index.php)

下面是一个完整的index.php文件,部署到Apache2本地服务器后即可运行,包含动态DOM操作和MathJax实时渲染的核心逻辑:

<?php
// 简单PHP入口,仅作为HTML载体,可按需扩展
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>动态MathJax示例</title>
    <!-- 引入MathJax资源 -->
    <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    <script>
        // MathJax基础配置
        MathJax = {
            tex: {
                inlineMath: [['$', '$'], ['\\(', '\\)']] // 行内公式标识
            },
            svg: {
                fontCache: 'global'
            }
        };
    </script>
    <style>
        .math-container {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 4px;
        }
        button {
            padding: 8px 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h2>动态添加并渲染数学公式</h2>
    <button onclick="addMathFormula()">添加新公式</button>
    <div id="math-content" class="math-container">
        <!-- 初始公式示例 -->
        <p>行内公式示例:$E=mc^2$</p>
        <p>块级公式示例:
            \[
            \sum_{n=1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}
            \]
        </p>
    </div>

    <script>
        // 动态添加数学公式并触发MathJax重新渲染
        function addMathFormula() {
            const contentDiv = document.getElementById('math-content');
            // 创建新的公式元素
            const newFormula = document.createElement('p');
            newFormula.innerHTML = `新添加的块级公式:
                \\[
                \\frac{d}{dx} \\left( \\int_{0}^{x} f(t) dt \\right) = f(x)
                \\]`;
            contentDiv.appendChild(newFormula);
            
            // 通知MathJax重新渲染新增的DOM元素
            MathJax.typesetPromise([newFormula]).catch(err => console.error(err));
        }
    </script>
</body>
</html>

使用说明

  • 将上述代码保存为index.php,放到Apache2的网站根目录(如/var/www/html/)
  • 启动Apache2服务后,访问http://localhost/index.php即可测试
  • 点击「添加新公式」按钮,可动态插入数学公式并自动完成渲染
  • 代码使用CDN加载MathJax,无需本地部署MathJax资源,确保服务器能访问外网即可

内容的提问来源于stack exchange,提问作者Joseph Vidal-Rosset

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 09:35:02