突出显示HTML文本中的单词(但不是标记) [英] Highlight word in HTML text (but not markup)

查看:192
本文介绍了突出显示HTML文本中的单词(但不是标记)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试突出显示正文中所有匹配的单词,而不是任何html标记内的单词。例如,给定的关键字是'para'。这是段落:

I'm trying to highlight all matching word inside the body but not words inside any html tag. For example the keyword given is 'para'. Here's the paragraph:

<p class="para"> Example of paragraph. Lorem ipsum dolor sit amet. </p>

导致:

<p class="para">
Example of <strong>para</strong>graph. Lorem ipsum dolor sit amet.
</p>

我知道这可以通过JavaScript的替换()但我对regex不太了解。

I know that this is possible with JavaScript's replace() but I just don't know much about regex.

推荐答案

演示: http://jsfiddle.net/crgTU/7/



Demo: http://jsfiddle.net/crgTU/7/

highlightWord(document.body,'para');

function highlightWord(root,word){
  textNodesUnder(root).forEach(highlightWords);

  function textNodesUnder(root){
    var n,a=[],w=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,null,false);
    while(n=w.nextNode()) a.push(n);
    return a;
  }

  function highlightWords(n){
    for (var i; (i=n.nodeValue.indexOf(word,i)) > -1; n=after){
      var after = n.splitText(i+word.length);
      var highlighted = n.splitText(i);
      var span = document.createElement('span');
      span.className = 'highlighted';
      span.appendChild(highlighted);
      after.parentNode.insertBefore(span,after);
    }
  }
}
​

你也可以考虑调用类似的东西......

You might also consider calling something like…

function removeHighlights(root){     
  [].forEach.call(root.querySelectorAll('span.highlighted'),function(el){
    el.parentNode.replaceChild(el.firstChild,el);
  });
}

...在你找到新的亮点之前(从DOM中删除旧的亮点) )。

…before you go finding the new highlights (to remove old highlights from the DOM).

这篇关于突出显示HTML文本中的单词(但不是标记)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆