0

我有一个内容可编辑的 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>

4

1 回答 1

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;
于 2013-09-07T14:45:27.550 回答