javascript - 高亮 - 如何使用javascript突出显示文本

谁能帮我写一个在网页上高亮文本的javascript函数,而且要求只高亮一次。

时间:

你可以使用jquery 高亮效果 。

但是,如果你对原始的javascript代码感兴趣,看看我的,只要复制粘贴到一个HTML中,打开文件,并且单击highlight,应该突出显示单词" fox"。


function highlight(text) {


 var inputText = document.getElementById("inputText");


 var innerHTML = inputText.innerHTML;


 var index = innerHTML.indexOf(text);


 if (index >= 0) { 


 innerHTML = innerHTML.substring(0,index) +"<span class='highlight'>" + innerHTML.substring(index,index+text.length) +"</span>" + innerHTML.substring(index + text.length);


 inputText.innerHTML = innerHTML;


 }


}

.highlight {


 background-color: yellow;


}

<button onclick="highlight('fox')">Highlight</button>



<div id="inputText">


 The fox went over the fence


</div>

编辑:

使用replace

你也可以轻松使用替换

"the fox jumped over the fence".replace(/fox/,"<span>fox</span>");

"the fox jumped over the other fox".replace(/fox/g,"<span>fox</span>");

要替换整个网页的HTML,你应该引用文档正文的innerHTML

document.body.innerHTML


function stylizeHighlightedString() {



 var text = window.getSelection();



 // For diagnostics


 var start = text.anchorOffset;


 var end = text.focusOffset - text.anchorOffset;



 range = window.getSelection().getRangeAt(0);



 var selectionContents = range.extractContents();


 var span = document.createElement("span");



 span.appendChild(selectionContents);



 span.style.backgroundColor ="yellow";


 span.style.color ="black";



 range.insertNode(span);


}



简单typeScript例子


module myApp.Search {


 'use strict';



 export class Utils {


 private static regexFlags = 'gi';


 private static wrapper = 'mark';



 private static wrap(match: string): string {


 return '<' + Utils.wrapper + '>' + match + '</' + Utils.wrapper + '>';


 }



 static highlightSearchTerm(term: string, searchResult: string): string {


 let regex = new RegExp(term, Utils.regexFlags);



 return searchResult.replace(regex, match => Utils.wrap(match));


 }


 }


}



然后构造实际结果:


module myApp.Search {


 'use strict';



 export class SearchResult {


 id: string;


 title: string;



 constructor(result, term?: string) {


 this.id = result.id;


 this.title = term ? Utils.highlightSearchTerm(term, result.title) : result.title;


 }


 }


}



以下是我用正则表达式纯JavaScript解决方案:


function highlight(text) {


 document.body.innerHTML = document.body.innerHTML.replace(


 new RegExp(text + '(?!([^<]+)?<)', 'gi'),


 '<b style="background-color:#ff0;font-size:100%">$&</b>'


 );


}



以下是我的尝试:


/**


 * Highlight keywords inside a DOM element


 * @param {string} elem Element to search for keywords in


 * @param {string[]} keywords Keywords to highlight


 * @param {boolean} caseSensitive Differenciate between capital and lowercase letters


 * @param {string} cls Class to apply to the highlighted keyword


 */


function highlight(elem, keywords, caseSensitive = false, cls = 'highlight') {


 const flags = caseSensitive ? 'gi' : 'g';


 // Sort longer matches first to avoid


 // highlighting keywords within keywords.


 keywords.sort((a, b) => b.length - a.length);


 Array.from(elem.childNodes).forEach(child => {


 const keywordRegex = RegExp(keywords.join('|'), flags);


 if (child.nodeType !== 3) { // not a text node


 highlight(child, keywords, caseSensitive, cls);


 } else if (keywordRegex.test(child.textContent)) {


 const frag = document.createDocumentFragment();


 let lastIdx = 0;


 child.textContent.replace(keywordRegex, (match, idx) => {


 const part = document.createTextNode(child.textContent.slice(lastIdx, idx));


 const highlighted = document.createElement('span');


 highlighted.textContent = match;


 highlighted.classList.add(cls);


 frag.appendChild(part);


 frag.appendChild(highlighted);


 lastIdx = idx + match.length;


 });


 const end = document.createTextNode(child.textContent.slice(lastIdx));


 frag.appendChild(end);


 child.parentNode.replaceChild(frag, child);


 }


 });


}



// Highlight all keywords found in the page


highlight(document.body, ['lorem', 'amet', 'autem']);

.highlight {


 background: lightpink;


}

<p>Hello world lorem ipsum dolor sit amet, consectetur adipisicing elit. Est vel accusantium totam, ipsum delectus et dignissimos mollitia!</p>


<p>


 Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, corporis.


 <small>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium autem voluptas perferendis dolores ducimus velit error voluptatem, qui rerum modi?</small>


</p>

如果你的关键字包含需要在正则表达式中转义的特殊字符,我还建议使用escape-string-regexp之类的东西:


const keywordRegex = RegExp(keywords.map(escapeRegexp).join('|')), flags);



因为HTML5可以使用<mark></mark>标签来实现Highlight文本,你可以使用javascript在标记间包含文本/关键字,下面是如何标记和取消标记文本的一个小例子。

JSFIDDLE DEMO

...