javascript - 如何使用 javascript 切换 MathJax 渲染与代码?

标签 javascript mathjax

如何切换 MathJax 的显示使用 javascript 渲染 View 和纯文本/代码 View 之间的等式?

例如,如何使用下面示例中的按钮来切换显示此等式:

$$x = {-b\pm\sqrt{b^2-4ac}\over 2a}.$$

以及运行代码片段时呈现的方程?

var btn = document.getElementById("math-toggle");

btn.onclick = function(event) { 
  // Toggle Math rendering here using MathJax API?
  alert("moo!"); 
};
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>MathJax example</title>
  <script type="text/javascript" async
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/latest.js?config=TeX-MML-AM_CHTML" async>
</script>
</head>
<body>
<button id="math-toggle">Toggle Math</button>

<p>
Equation:  $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
</p>
</body>
</html>

最佳答案

一种方法(使用 MathJax API)是使用 PlainSource 输出并重新渲染。

根据具体情况,在应用程序中跟踪这一点可能会更容易(例如,只需获取 MathJax 创建的脚本标记的内容)。

由于用于 TeX 的分隔符仅在预处理阶段发挥作用(并且是用户可配置的),因此需要额外的逻辑来跟踪它。

var btn = document.getElementById("math-toggle");

btn.onclick = function(event) {
  if (!btn.checked) {
    MathJax.Hub.Queue(["setRenderer", MathJax.Hub, "CommonHTML"]);
    MathJax.Hub.Queue(["Rerender", MathJax.Hub]);
  } else {
    MathJax.Hub.Queue(["setRenderer", MathJax.Hub, "PlainSource"]);
    MathJax.Hub.Queue(["Rerender", MathJax.Hub]);

  }
};
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>MathJax example</title>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/latest.js?config=TeX-MML-AM_CHTML">
  </script>
</head>

<body>
  <input id="math-toggle" type="checkbox"  name="mathjax-switch" >
  <label id="mathjax-switch">Replace with plain text source</label>
  <p>
    Equation: $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
  </p>
</body>

</html>

关于javascript - 如何使用 javascript 切换 MathJax 渲染与代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50693108/

相关文章:

javascript - 在加载 CGI 脚本之前等待页面加载?

latex - MathJax 无法在 Github 页面上正确渲染某些方程

github - 在 Github 页面上使用 MathJax?

styling - 在移动设备上调整 Mathjax 的大小

javascript - Reactjs 子组件在设置父组件在 props 中提供的状态数组时进入无限循环

javascript - setInterval() 方法创建奇怪的重叠

javascript - Vue 组件在 <template> html 标签中不可见

mathjax - 为什么 MathJax.js 生成的 svg 与 MathJax-node 生成的 svg 不同

javascript - 实现 MathJax : Using JSFiddle, Canvas 和 DOM

javascript - 预览图像而不上传到我的服务器