高效地突出显示文档(JavaScript)中的文本 [英] Highlighting text in document (JavaScript) Efficiently

查看:76
本文介绍了高效地突出显示文档(JavaScript)中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何(有效地 - 不会减慢计算机[cpu])突出显示页面的特定部分?

How can I (efficiently - not slowing the computer [cpu]) highlight a specific part of a page?

假设我的页面如此:

<html>
<head>
</head>
<body>
"My generic words would be selected here" !.
<script>
//highlight code here
var textToHighlight = 'selected here" !';
//what sould I write here?
</script>
</body>
</html>

我的想法是克隆所有将body转换为变量并通过indexOf查找指定的文本,更改(插入带有background-color的span)cloned字符串并将real正文替换为cloned字符。

I只是觉得效率不高。

你还有其他想法吗?(有创意:))

My idea is to "clone" all the body into a variable and find via indexOf the specified text, change(insert a span with a background-color) the "cloned" string and replace the "real" body with the "cloned" one.
I just think that it isn't efficient.
Do you have any other ideas? (be creative :) )

推荐答案

<html>
<head>
</head>
<body>
<p id="myText">"My generic words would be selected here" !.</p>
<script>
//highlight code here
var textToHighlight = 'selected here" !';
var text = document.getElementById("myText").innerHTML
document.getElementById("myText").innerHTML = text.replace(textToHighlight, '<span style="color:red">'+textToHighlight+'</span>');
//what sould I write here?
</script>
</body>
</html>

这篇关于高效地突出显示文档(JavaScript)中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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