如何突出显示js中公式和文本的混合部分?

时间:2019-01-30 08:00:13

标签: javascript selection

我想要看到的最终结果: the final result i want to see

背景:我想在html格式的数学文章中做笔记,但是我不知道如何标记网页中每个突出显示的“句子”,尤其是在公式和文字。

相关问题: Javascript Quandary: Creating a highlighter pen tool... almost there

简单示例:

   <style>
    ::selection {
    background: yellow;
}

::-moz-selection {
    background: yellow;
}
</style>
<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>

<div onmouseup="highlightSelection('yellow')">
    The jury trial is one of the handful of democratic
<br>
    institutions that allow <b>individual citizens</b>, rather than
<br>
the government, to make important societal decisions.
<br>
A crucial component of the jury trial, at least in serious
<br>
criminal cases, is the rule that verdicts be unanimous
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}.$$

</div>


<script>
    function makeEditableAndHighlight(colour) {
    var range, sel = window.getSelection();
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    document.designMode = "on";
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    // Use HiliteColor since some browsers apply BackColor to the whole block
    if (!document.execCommand("HiliteColor", false, colour)) {
        document.execCommand("BackColor", false, colour);
    }
    document.designMode = "off";
}

function highlightSelection(colour) {
    var range, sel;
    if (window.getSelection) {
        // IE9 and non-IE
        try {
            if (!document.execCommand("BackColor", false, colour)) {
                makeEditableAndHighlight(colour);
            }
        } catch (ex) {
            makeEditableAndHighlight(colour)
        }
    } else if (document.selection && document.selection.createRange) {
        // IE <= 8 case
        range = document.selection.createRange();
        range.execCommand("BackColor", false, colour);
    }
}

</script>

0 个答案:

没有答案