javascript突出显示字符

javascript highlighting of characters

本文关键字:字符 显示 javascript      更新时间:2023-09-26

如何突出显示(或给出任何特殊标记)像‘’“”‛‟′″˝这样的特殊字符?谢谢使用查找和替换.innerHTML.replace()不起作用,因为它会破坏事件处理程序和DOM。


我已经尝试了以下操作,但最终只是以纯文本而不是代码的形式出现了span

function highlightText(node, find, rep){
    if(node){
        node= node.firstChild;
        while(node!= null){
            if(node.nodeType== 3){
                node.data= node.data.replace(find, rep);
            }
            else highlightText(node, find, rep);
            node= node.nextSibling;
        }
    }
    return true;
}
highlightText(document.body,/‘/g, "<span style='background: red; color: white;'>‘</span>")
highlightText(document.body,/’/g, "<span style='background: red; color: white;'>’</span>")
highlightText(document.body,/“/g, "<span style='background: red; color: white;'>“</span>")
highlightText(document.body,/”/g, "<span style='background: red; color: white;'>”</span>")
highlightText(document.body,/‛/g, "<span style='background: red; color: white;'>‛</span>")
highlightText(document.body,/‟/g, "<span style='background: red; color: white;'>‟</span>")
highlightText(document.body,/′/g, "<span style='background: red; color: white;'>′</span>")
highlightText(document.body,/″/g, "<span style='background: red; color: white;'>″</span>")
highlightText(document.body,/˝/g, "<span style='background: red; color: white;'>˝</span>")

以下是一些适用于所有主流浏览器的代码。我以前在Stack Overflow上发布过这个代码的变体(例如,这里、这里和这里),并使它变得很好和通用,所以我(或其他任何人)不必为了重用它而对它进行太多更改

jsFiddle示例:http://jsfiddle.net/eh8FE/

代码:

// Reusable generic function
function surroundInElement(el, regex, surrounderCreateFunc) {
    // script and style elements are left alone
    if (!/^(script|style)$/.test(el.tagName)) {
        var child = el.lastChild;
        while (child) {
            if (child.nodeType == 1) {
                surroundInElement(child, regex, surrounderCreateFunc);
            } else if (child.nodeType == 3) {
                surroundMatchingText(child, regex, surrounderCreateFunc);
            }
            child = child.previousSibling;
        }
    }
}
// Reusable generic function
function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
    var parent = textNode.parentNode;
    var result, surroundingNode, matchedTextNode, matchLength, matchedText;
    while ( textNode && (result = regex.exec(textNode.data)) ) {
        matchedTextNode = textNode.splitText(result.index);
        matchedText = result[0];
        matchLength = matchedText.length;
        textNode = (matchedTextNode.length > matchLength) ?
            matchedTextNode.splitText(matchLength) : null;
        surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
        parent.insertBefore(surroundingNode, matchedTextNode);
        parent.removeChild(matchedTextNode);
    }
}
// This function does the surrounding for every matched piece of text
// and can be customized  to do what you like
function createSpan(matchedTextNode) {
    var el = document.createElement("span");
    el.style.backgroundColor = "red";
    el.style.color = "white";
    el.appendChild(matchedTextNode);
    return el;
}
// The main function
function wrapSpecialChars(container) {
    surroundInElement(container, /[‘’“”‛‟′″˝]+/, createSpan);
}
wrapSpecialChars(document.body);
更改HTML中任何文本格式的唯一方法是在文本周围的HTML元素上定义样式。因此,如果您只想突出显示某些字符,那么这些字符必须分别用一个HTML元素包装,通常是span,尽管您可能更具语义。

因此,我不确定您所说的"破坏事件处理程序和DOM"是什么意思,但您必须修改DOM以突出显示字符。这是没有办法的。

我知道,如果替换innerHTML的整棵树,这些节点将被删除,然后添加新的节点。然而,在不知道您已经在处理什么的情况下,我们无法真正为您提供替代方案。


如果你真的想在整个页面上突出显示一些字符,你必须做到无损:

  1. 创建一个递归操作的函数
  2. 在作为参数的节点的所有子节点上迭代
  3. 如果节点是一个元素,则使用新节点自递归调用
  4. 如果该节点是一个文本节点,请将该文本节点替换为HTML,并将所需范围中的字符换行
  5. 使用要替换的内容的根节点调用上述函数

您可以为此使用特殊的对象函数。JQuery可以帮助您在短时间内完成此操作。

例如,您可以更改对象的样式,以便在加载页面时高亮显示。这里有一个主要的想法。

<body onload='highlight()'>
...
</body>

其中

function highlightSpan( content )
{
  return "<span style='background: yellow'>" + content + "</span>";
}
function hightlight()
{
  var highlightChars = "‘’“”‛‟′″˝";
  // change body content (and highlight chars)
  var bodyContent = $( "body" ).html();
  for( var i = 0; i < highlightChars.length; i++ )
  {
     var highlightChar = highlightChars[ i ];
     bodyContent = bodyContent.replace( highlightChar, highlightSpan( highlightChar ) );
  }
  $( "body" ).html( bodyContent );
}

您可以使用document.getElementsByTagName("body")[0].ninnerHTML而不是$("body").html().

可能是replace()将只替换一个匹配的第一个字符。因此,您可以使用替换(/('|'|"|"|"|"|")/g,highlightSpan(something))。并用~这一特殊正则表达式字符来解决问题。