前端整合MathjaxJS的配置笔记
in Note with 7 comments
前端整合MathjaxJS的配置笔记
in Note with 7 comments

这篇文章是我给Pinghsu主题添加数学公式功能的一个小教程,包含我大量的官方文档阅读后的实践,跟着这篇配置教程走,你可以做到给任何一个需要数学公式的站点添加支持。

教程如标题所述是针对 Mathjax 的实践,我简单了解一下 KaTex ,也是个不错的选择。

MathJax简介

MathJax是一款运行在浏览器中的开源的数学符号渲染引擎,使用MathJax可以方便的在浏览器中显示数学公式,不需要使用图片。目前,MathJax可以解析Latex、MathML和ASCIIMathML的标记语言。(Wiki)

引入MathJax

在页脚处,引入官方的cdn

<script src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

官方cdn的js在国内访问慢,所以我们一般引入的是国内的公共资源cdn提供的js,这里特别感谢BootCDN

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

但这个js还是会调用到 cdn.mathjax.org 里的一些配置js文件,我们最好在head内加一个dns-prefetch,用于网页加速,了解更多可以访问我另外一篇文章:here

<link rel="dns-prefetch" href="//cdn.bootcss.com" />
<link rel="dns-prefetch" href="//cdn.mathjax.org" />

外联config说明

我们引入MathJax,发现链接后面多了个?config=TeX-AMS-MML_HTMLorMML

这个多出来的东西其实是告诉MathJax,我们要用到的叫TeX-AMS-MML_HTMLorMML.js的配置文件,其用来控制显示数学公式的HTMl显示输出

这个配置文件其实也可以通过指定URL获取,官方例子如下

<script type="text/javascript"
   src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML,http://myserver.com/MathJax/config/local/local.js">
</script>

MathJax.js也用到其他js,这些js都来自官方的cdn里,所以这也是解释了上面为什么我们需要对官方cdn进行加速

下面是官方更详细的TeX-AMS-MML_HTMLorMML配置文件的说明

This configuration file is the most general of the pre-defined configurations. It loads all the important MathJax components, including the TeX and MathML preprocessors and input processors, the AMSmath, AMSsymbols, noErrors, and noUndefined TeX extensions, both the native MathML and HTML-with-CSS output processor definitions, and the MathMenu and MathZoom extensions.

In addition, it loads the mml Element Jax, the TeX and MathML input jax main code (not just the definition files), as well as the toMathML extension, which is used by the Show Source option in the MathJax contextual menu. The full version also loads both the HTML-CSS and NativeMML output jax main code, plus the HTML-CSS mtable extension, which is normally loaded on demand.

更多配置文件信息请看:here

内联config说明

与此同时,官方其实还提供了一个能让我们内联一个配置选项的功能

很简单就是使用<script></script>标签对,但注意的是需要声明类型type="text/x-mathjax-config"。要想让这个内联配置生效就得放在MathJax.js之前,例子如下

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
});
</script>
<script type="text/javascript" src="path-to-MathJax/MathJax.js"></script>

其中MathJax.Hub.Config()里的配置选项是本篇文章的重点

识别公式

我们可以通过MathJax.Hub.Config()tex2jax去实现公式识别

官方例子,如下

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
    }
});
</script>
<script type="text/javascript" src="path-to-MathJax/MathJax.js"></script>

其中inlineMath识别的单行内的数学公式,我们可以通过$ ... $\\( ... \\)去识别这种数学公式

效果如下:

When \( a \ne 0 \), there are two solutions to \( (ax^2 + bx + c = 0) \)

那么displayMath就是识别整个独立段落的数学公式并且居中显示,我们可以通过$$ ... $$\\[ ... \\]去识别这种数学公式

效果如下:

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

在中文世界里,我们往往喜欢用()或者[]去备注或者圈住重要的字段,所以在一般情况下我们并不需要\( ... \)\[ ... \]去识别公式

但也会有遇到两个$$的情况造成误伤,别急,先看完,你就知道怎么解决了

区域选择性识别

约束识别范围

我们的数学公式通常是在文章里,那么如何实现只在文章的标签对里面去做公式识别,如下

var mathId = document.getElementById("post-content");
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
    }
});
MathJax.Hub.Queue(["Typeset",MathJax.Hub,mathId]);

默认情况下,MathJax.Hub.Queue(["Typeset",MathJax.Hub])是对整个DOM树进行识别的

我们要约束识别范围,官方文档告诉我们MathJax.Hub.Queue的第三个参数就是识别范围,上面的代码就是告诉我们要在id为post-content的标签内去做公式识别

避开特殊标签和Class

还有其他方法吗?

有,那就是避开一些特殊的标签或者Class,如下

MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre','code','a'],
        ignoreClass:"class1"
    }
});
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);

其中skipTags用来避开一些特殊的标签,这里避开是script,noscript,style,textarea,pre,code,a的标签内

ignoreClass用来避开标签内声明的CSS Class属性,这里避开的是带有class="class1"的标签内

如果我们不想让mathjax识别评论里的公式就可以用ignoreClass

如果有多个Class需要避开,我们可以通过 | 来区分,写成ignoreClass: "class1|class2"就可以了

更多

获取更多tex2jax的配置信息访问:here

美化数学公式

去掉蓝框

outline-gongshi-12312476781.png

上图所示的是,点击该公式时周围有一圈蓝色的边框,我们可以通过添加CSS去掉,如下

.MathJax{outline:0;}

如果要改变字体大小,如下

.MathJax span{font-size:15px;}

公式太长的时候会溢出,解决如下

.MathJax_Display{overflow-x:auto;overflow-y:hidden;}

扩展功能

为了更好实现美化数学公式,我们需要扩展一下MathJax.Hub.Config(),如下

MathJax.Hub.Config({
    extensions: ["tex2jax.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre','code','a'],
        ignoreClass:"class1"
    },
    "HTML-CSS": {
    }
});
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);

我们可以在HTML-CSS添加可用字体,如下

"HTML-CSS": {
    availableFonts: ["STIX","TeX"]
}

我们要关闭下图的公式右击菜单

gongshi-caidan-123579702.png

也是在HTML-CSS添加设置,如下

"HTML-CSS": {
    showMathMenu: false
}

去掉加载信息

Mathjax.js在加载的时候,我们可以在网页左下角看到加载情况,可以直接在MathJax.Hub.Config()里配置去掉,如下

MathJax.Hub.Config({
    showProcessingMessages: false,
    messageStyle: "none"
});

整理

这里我整理两份可以整合到主题的代码,请根据自己的需要修改,简单注释了一下

整理一

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    showProcessingMessages: false, //关闭js加载过程信息
    messageStyle: "none", //不显示信息
    extensions: ["tex2jax.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ], //行内公式选择符
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ], //段内公式选择符
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre','code','a'], //避开某些标签
        ignoreClass:"comment-content" //避开含该Class的标签
    },
    "HTML-CSS": {
        availableFonts: ["STIX","TeX"], //可选字体
        showMathMenu: false //关闭右击菜单显示
    }
});
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
</script>
<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

整理二

<script type="text/x-mathjax-config">
var mathId = document.getElementById("post-content"); //选择公式识别范围
MathJax.Hub.Config({
    showProcessingMessages: false, //关闭js加载过程信息
    messageStyle: "none", //不显示信息
    extensions: ["tex2jax.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"] ], //行内公式选择符
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ], //段内公式选择符
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre','code','a'] //避开某些标签
    },
    "HTML-CSS": {
        availableFonts: ["STIX","TeX"], //可选字体
        showMathMenu: false //关闭右击菜单显示
    }
});
MathJax.Hub.Queue(["Typeset",MathJax.Hub,mathId]);
</script>
<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

配合的css

.MathJax_Display{overflow-x:auto;overflow-y:hidden;}
.MathJax{outline:0;}

InstantClick回调

代码如下

适用于整理一的代码

<script data-no-instant>
InstantClick.on('change', function(isInitialLoad){
    if (isInitialLoad === false) {
        if (typeof MathJax !== 'undefined'){
            MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
        }
    }
});
InstantClick.init();
</script>

适用于整理二的代码

<script data-no-instant>
InstantClick.on('change', function(isInitialLoad){
    if (isInitialLoad === false) {
        if (typeof MathJax !== 'undefined'){
            var mathId = document.getElementById("post-content");
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,mathId]);
        }
    }
});
InstantClick.init();
</script>

结语

写了好久···

我还会再写一篇关于数学公式语法···

Responses
  1. JasonXu

    博主你好,hexo中的mathjax怎么添加css去掉蓝框呢

    Reply
  2. gakki

    请问hexo的mathjax怎么取消左下角的加载信息?

    Reply
    1. @gakki

      一样一样的。
      hexo有插件支持的,https://github.com/akfish/hexo-math

      Reply
  3. kam

    style.ccss的132行:
    background-position: 50% 50%; 改为 background-position: 50% 0%;
    background-size: cover; 删除

    首页配图不会模糊。

    Reply
    1. @kam

      这样做,对于我这种小的缩略图可能效果会更好;
      问题是这个主题是准备开源的,面对的缩略图是大小不一样,所以只能这样写。
      😚 谢谢哟~

      Reply
      1. Kam
        @Chakhsu Lau

        你百度 timthumb.php

        Reply
        1. @Kam

          有了解过,但这个东西好旧好废啊,而且这个东西已经没人支持去更新维护了,如下链接
          https://www.binarymoon.co.uk/2014/09/timthumb-end-life/

          还是让用户自己对自己的缩略图负责吧,我都准备将博客所有的缩略图换了。
          因为这次是高度是250px,我会换成500px,宽度自适应,这样也就支持了HIDPI了。

          Reply