如何使用javascript突出显示文本 [英] How to highlight text using javascript
问题描述
有人可以帮助我使用可以突出显示网页上文字的javascript功能。
并且要求是 - 只突出一次,而不是像搜索一样突出显示所有出现的文本。
Can someone help me with a javascript function that can highlight text on a web page. And the requirement is to - highlight only once, not like highlight all occurrences of the text as we do in case of search.
推荐答案
您可以使用jquery 突出显示效果。
You can use the jquery highlight effect.
但如果您对原始javascript代码感兴趣,请查看我得到的内容
只需将粘贴复制到HTML中,打开文件并单击突出显示 - 这应突出显示单词狐狸。表现明智我认为这可以用于小文本和单个重复(如您指定的)
But if you are interested in raw javascript code, take a look at what I got Simply copy paste into an HTML, open the file and click "highlight" - this should highlight the word "fox". Performance wise I think this would do for small text and a single repetition (like you specified)
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>
编辑:
我看到这个答案增加了一些人气,我想我可能会加上它。
你也可以轻松使用替换
I see this answer gained some popularity, I thought I might add on it. You can also easily use replace
狐狸跳过篱笆.replace(/ fox /,< span> ; fox< / span>);
或多次出现(与问题无关,但在评论中被问到)你只是在替换正则表达式上添加全局
。
Or for multiple occurrences (not relevant for the question, but was asked in comments) you simply add global
on the replace regular expression.
狐狸跳过另一只狐狸.replace(/ fox / g,< span> fox< / span>) ;
希望这对有吸引力的评论者有所帮助。
Hope this helps to the intrigued commenters.
替换整个网页的HTML,你应该参考文件正文的 innerHTML
。
to replace the HTML for an entire web-page, you should refer to innerHTML
of the document's body.
document.body.innerHTML
这篇关于如何使用javascript突出显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!