在网页中写入数学公式

今天跟大家分享在网页中使用数学公式。

像这样的公式大家怎么写出来呢?

甚至还有更复杂的:

以前有一种很常见的做法,就是利用数学公式生成器生成一张图片,然后将图片嵌在网页里。

就是先用这个数学公式生成器生成公式的图片,然后在将该img的style属性改成  style="padding:0px;border: none;margin:0px;vertical-align: bottom;"   插入到网页中就可以了。

这种方法可以利用阮一峰的数学公式生成器。具体做法去他的博客看,我就不搬运了:阮一峰数学生成器博客(点击我)。

但是,有时候我们不想在网页中嵌入图片,就是不用图片这种方法怎么去实现呢?答案是利用Mahtjax这个插件。首先上官网:Mathjax官网,然后是github的资料:GitHub,最后还有一个英文文档:文档

这些都是我查找的资料,我说一下简单的使用方法。

第一步先是引入:你可以通过引入CDN,也可以下载js引入,个人推荐CDN引入。

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

上述的configure支持了TeX和MathLL语法,如果需要支持AsciiMath语法,将configure改为“?config=TeX-AMS=MML_HTMLorMML”

第二步:有3种使用方法:
①:
TeX and LaTeX格式方式
默认运算符是$$...$$和\[... \]为显示数学,\(...\)用于在线数学。请特别注意,在$...$在线分隔符不使用默认值。这是因为,美元符号出现常常在非数学设置,这可能会导致一些文本被视为意外数学。例如,对于单元分隔符,“...的费用是为第一个$2.50和$2.00每增加一...”将导致短语“2.50的第一个,和”被视为数学因为它属于美元符号之间。注意HTML的标签与TeX语法可能有冲突,“小于号/大于号/ampersands&”需要前后空格,比如:$$a < b$$
为了防止出错,加上一段js代码,例子如下:
<!DOCTYPE html>
<html>
<head>
<title>MathJax TeX Test Page</title>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/javascript"
  src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>
When $a \ne 0$, there are two solutions to \(ax^2 + bx + c = 0\) and they are
$$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
</body>
</html>

 ②:第二种方法:添加MathML中等标签的形式

 

<!DOCTYPE html>
<html>
<head>
<title>MathJax MathML Test Page</title>
<script type="text/javascript"
  src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
</head>
<body>

<p>
When
<math xmlns="http://www.w3.org/1998/Math/MathML">
  <mi>a</mi><mo>&#x2260;</mo><mn>0</mn>
</math>,
there are two solutions to
<math xmlns="http://www.w3.org/1998/Math/MathML">
  <mi>a</mi><msup><mi>x</mi><mn>2</mn></msup>
  <mo>+</mo> <mi>b</mi><mi>x</mi>
  <mo>+</mo> <mi>c</mi> <mo>=</mo> <mn>0</mn>
</math>
and they are
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
  <mi>x</mi> <mo>=</mo>
  <mrow>
    <mfrac>
      <mrow>
        <mo>&#x2212;</mo>
        <mi>b</mi>
        <mo>&#x00B1;</mo>
        <msqrt>
          <msup><mi>b</mi><mn>2</mn></msup>
          <mo>&#x2212;</mo>
          <mn>4</mn><mi>a</mi><mi>c</mi>
        </msqrt>
      </mrow>
      <mrow> <mn>2</mn><mi>a</mi> </mrow>
    </mfrac>
  </mrow>
  <mtext>.</mtext>
</math>
</p>

</body>
</html>

 ③第三种:AsciiMath输入。以``为符号。

<!DOCTYPE html>
<html>
<head>
<title>MathJax AsciiMath Test Page</title>
<script type="text/javascript"
  src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=AM_HTMLorMML-full"></script>
</head>
<body>

<p>When `a != 0`, there are two solutions to `ax^2 + bx + c = 0` and
they are</p>
<p style="text-align:center">
  `x = (-b +- sqrt(b^2-4ac))/(2a) .`
</p>

</body>
</html>

运行结果都是这样子的

DONE

posted @ 2015-11-12 10:50  ZQ是水鱼  阅读(11239)  评论(0编辑  收藏  举报