我有一个内容可编辑的div,而JS函数用于搜索某些单词的输入。如果找到匹配,div的内容将变为蓝色,但我希望仅匹配的单词变为蓝色。我怎样才能做到这一点? 这是我的JS ......
function init() {
window.setInterval(function() {
var div = document.getElementById("texty");
var html = div.innerHTML;
var buzzword = ["function","()","{", "}","[", "]",".getElementById", ".getElementsByClassName",".style","$"];
for(var i = 0; i < buzzword.length; i++)
{
var regex = new RegExp(buzzword[i], 'g');
html = html.replace(regex, "<span style='color:blue'>" + buzzword[i] + "</span>");
}
div.innerHTML = html;
}, 100);
}
我的HTML就是这个......
<div id="texty" contenteditable="true" onfocus="init()"></div>
答案 0 :(得分:0)
获取div的html然后执行正则表达式替换并在单词周围添加一个范围。代码看起来像这样:
var escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
var div = document.getElementById("texty");
var html = div.innerHTML;
var buzzword = ["function","()","{", "}","[", "]",".getElementById", ".getElementsByClassName",".style","$"];
for(var i = 0; i < buzzword.length; i++)
{
var regex = new RegExp(escape(buzzword[i]), 'g');
html = html.replace(regex, "<span style='color:blue'>" + buzzword[i] + "</span>");
}
div.innerHTML = html;