在javascript中更改输入中匹配文本的文本颜色

时间:2015-06-18 08:44:40

标签: javascript regex

这是我的代码

我正在尝试更改<li>元素中与<input>元素中的文本匹配的任何匹配项的颜色。因此,如果您键入,请说“这是一个简单的文本”,结果应如下所示:

<input value="this is a simple text" id="term"/> 
<ul id="ul-id" >
    <li id="li-id-1"> hello budy <span style="color:red">this</span> <span style="color:red">is</span> really <span style="color:red">simple</span> stuff </li>
    <li id="li-id-2"> <span style="color:red">this</span> <span style="color:red">is</span> it</li>
    <li id="li-id-3"> there <span style="color:red">is</span> something here</li>
    <li id="li-id-4"> plain <span style="color:red">text</span> file</li>
</ul>

任何帮助都将不胜感激。

谢谢。

7 个答案:

答案 0 :(得分:2)

如果您愿意,可以删除delay功能,但这会导致性能下降:

// https://stackoverflow.com/a/9310752/1636522
RegExp.escape = function (text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
};

window.addEventListener('load', function () {
    var wrapper = '<span style="background:yellow">$&</span>';
    var input = document.getElementById('term');
    var list = document.getElementById('ul-id');
    var items = list.getElementsByTagName('li');
    var l = items.length;
    var source = Array.prototype.map.call(
        items, function (li) { return li.textContent; }
    );
    var cmp = function (a, b) {
        return b.length - a.length;
    };
    var delay = function (fn, ms) {
        var id, scope, args;
        return function () {
            scope = this;
            args = arguments;
            id && clearTimeout(id);
            id = setTimeout(function () { 
                fn.apply(scope, args); 
            }, ms);
        };
    };
    term.addEventListener('keyup', delay(function () {
        var i, re, val;
        if (val = this.value.match(/[^ ]+/g)) {
            val = val.sort(cmp).map(RegExp.escape);
            re = new RegExp(val.join('|'), 'g');
            for (i = 0; i < l; i++) {
                items[i].innerHTML = source[i].replace(re, wrapper);
            }
        }
        else {
            for (i = 0; i < l; i++) {
                items[i].textContent = source[i];
            }
        }
    }, 500));
});
<input value="" id="term"/> 
<ul id="ul-id" >
    <li id="li-id-1"> hello budy this is really simple stuff </li>
    <li id="li-id-2"> this is it</li>
    <li id="li-id-3"> there is something here</li>
    <li id="li-id-4"> plain text file</li>
</ul>

类似主题:https://stackoverflow.com/a/20427785/1636522

答案 1 :(得分:1)

我不知道是否只有RegEx是可能的,但这是一个jQuery解决方案:

$('#term').change(function() {
    var inpArr = $(this).val().split(" ");

    $('#ul-id li').each(function() {
        var liArr = $(this).text().split(" ");
        var txt = "";
        $.each(liArr, function(i, v) {
            if(inpArr.indexOf(v) > -1) {
                txt += "<span class='red'>"+ v +"</span> ";
            } else {
                txt += v + " ";
            }
        });
        $(this).html(txt);
    });
});

span.red {
     color: red; 
}

工作小提琴:https://jsfiddle.net/ermk32yc/1/

答案 2 :(得分:1)

普通JS解决方案

&#13;
&#13;
var list = document.querySelector('#ul-id'),
    listItem,
    listItems,
    term = document.querySelector('#term'),
    oldRef = list.innerHTML,
    oldValue;

term.addEventListener('keyup', function () {
    var regExp,
        value = term.value;

    if (oldValue !== value) {
        oldValue = value;
    
        // Reset
        list.innerHTML = oldRef;
    
        if (value.trim() !== '') {
            listItems = list.querySelectorAll('#ul-id li');
            regExp = new RegExp(term.value, 'g');

            // Perform matching
            for (var i = 0; i < listItems.length; i++) {
                listItem = listItems[i];
                listItem.innerHTML = listItem.innerHTML.replace(regExp, function (match) {
                    return '<span class="matched">' + match + '</span>';
                });
            }
        }
    }

}, false);
&#13;
.matched {
    color: red;
}
&#13;
<input  id="term"/> 

<ul id="ul-id" >

    <li id="li-id-1"> hello budy this is really simple stuff </li>
    <li id="li-id-2"> this is it</li>
    <li id="li-id-3"> there is something here</li>
    <li id="li-id-4"> plain text file</li>

</ul>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

你可能会做这样的事情

$('#term').change(function (i) {
    var terms = $('#term').val().split(" ");
    $('#ul-id > li').each(function (i, el) {
        var val = $(el).html().replace(/<[^<]+>/g, ''),
            match;
        terms.forEach(function (term) {
            val = val.replace(new RegExp(term, 'g'),
                '<span style="color:red">' + term + '</span>');
        });
        $(el).html(val);
    });
});

https://jsfiddle.net/1vm0259x/5/

答案 4 :(得分:0)

使用jQuery

if (!RegExp.escape) {
  RegExp.escape = function(value) {
    return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
  };
}

$('#term').on('change keyup', function() {
  //$('#ul-id li .highlight').contents().unwrap();//remove previous highlights

  var parts = this.value.split(' ').map(function(value) {
    return '\\b' + RegExp.escape(value) + '\\b';
  });
  var regex = new RegExp(parts.join('|'), 'g');

  $('#ul-id li ').each(function() {
    var text = $(this).text();
    $(this).html(text.replace(regex, function(part) {
      return '<span class="highlight">' + part + '</span>'
    }))
  })
});
.highlight {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="term" />
<ul id="ul-id">
  <li id="li-id-1">hello budy this is really simple stuff</li>
  <li id="li-id-2">this is it</li>
  <li id="li-id-3">there is something here</li>
  <li id="li-id-4">plain text file</li>
</ul>

答案 5 :(得分:0)

如果li elemnets

中没有html内容,您可以使用以下解决方案

if (!RegExp.escape) {
  RegExp.escape = function(value) {
    return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
  };
}

var lis = [].slice.call(document.querySelectorAll('#ul-id li'));
lis.forEach(function(el) {
  el.dataset.text = el.innerHTML;
});

document.querySelector('#term').addEventListener('change', function() {
  var parts = this.value.split(' ').map(function(value) {
    return '\\b' + RegExp.escape(value) + '\\b';
  });
  var regex = new RegExp(parts.join('|'), 'g');

  lis.forEach(function(el) {
    el.innerHTML = el.dataset.text.replace(regex, function(part) {
      return '<span class="highlight">' + part + '</span>'
    })
  });
});
.highlight {
  color: red;
}
<input id="term" />
<ul id="ul-id">
  <li id="li-id-1">hello budy this is really simple stuff</li>
  <li id="li-id-2">this is it</li>
  <li id="li-id-3">there is something here</li>
  <li id="li-id-4">plain text file</li>
</ul>

答案 6 :(得分:0)

您可以处理模糊事件,也可以将内部功能代码复制粘贴到需要的位置。这是指导代码,您可以根据需要更多地探索匹配功能,然后可以遍历您的li元素,如下所示。

$('#term).blur(function() {

  $('#ul-id li').foreach(function()
  {
   if($(this).text().match($("#term").text()))
   {
     ///set/change here  color of  li element
      $(this).css('color', 'red');
   }
  }
}