English 中文(简体)
HTML 文本中突出显示单词( 但不是标记)
原标题:Highlight word in HTML text (but not markup)

我试图突出显示身体内所有匹配的单词, 而不是任何 html 标签内的单词。 例如, 给定的关键字是第 段 。 这里的段落 :

<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 s replace () () ) 是可以做到的,但我对regex不太了解。

最佳回答

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);
    }
  }
}
​

你也可以考虑打个电话 比如说...

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

...在你找到新的亮点之前(去掉DOM的旧亮点)

问题回答

Why using a selfmade highlighting function is a bad idea

开始从零开始建立您自己的突出功能可能是个坏主意, 原因是因为您肯定会遇到其他人已经解决的问题。 挑战 :

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I m talking about cross-browser tests!

听上去复杂吗? 如果您想要一些特征 比如忽略一些元素 从突出显示, diacritics映射,同义词映射, 在 iframes 内部搜索, 分开的单词搜索等等。 这变得越来越复杂 。

Use an existing plugin

当使用一个已有的、实施良好的插件时, 您不必担心上面提到的插件。 文章 < stronga href=" https://www. sitepoint.com/ 10- jquery- text- highlighter- plugins/ " rel=“ nofollow” > 10jQuery 文本提示插件 与流行的突顯插件相比, 在站点上的插件 < /a/ strong> 。

Have a look at mark.js

< a href=" "https://markjs.io/" rel="nofollow">mark.js 是一个以纯 JavaScript 写成的插件,但也可以作为 jQuery 插件。 开发该插件是为了提供比其他插件更多的机会, 可以选择 :

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms

https://markjs.io/configurator.html" rel=“nofollow” >DEMO

也可以见“https://jsfiddle.net/julmot/vpav6tL1/" rel=“no follow”>这个小提琴

<强度 > 用户示例 :

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

它在GitHub上自由开发了开放源码(项目参考资料 )。

You can use the regexp way but it won t highlight over several tags yet. For exampel myhighlight the words "my highlights" will not be highlighted.

这是代码:

str= <img src="brown fox.jpg" title="The brown fox" /> 
    + <p>some text containing fox. And onother fox.</p> 
var word="fox";
word="(\b"+ 
    word.replace(/([{}()[]\.?*+^$|=!:~-])/g, "\$1")
        + "\b)";
var r = new RegExp(word,"igm")
str.replace(/(>[^<]+)/igm,function(a){
    return a.replace(r,"<span class= hl >$1</span>");
})




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签