Highlighting search words like Chrome with jQuery

前端 未结 3 831
我在风中等你
我在风中等你 2020-12-19 12:52

I have recently done a very simple highlighting with jQuery and a highlight plugin. It looks like this:

$(\'myButton\').click(function() {

相关标签:
3条回答
  • 2020-12-19 13:00

    I've edited JAndy's code so the result would match all the occurences in the text and the search would not be case-sensitive. Link Hope someone finds this helpful

    0 讨论(0)
  • 2020-12-19 13:16

    I made quick excersise out of it, code:

        $(document).ready(function(){
        var search = ['p', 'div', 'span'];
    
        $("#highlighter").bind('keyup', function(e){
        var pattern = $(this).val();
    
        $.each(search, function(i){
            var str = this[0];        
            var orgText = $(str).text();
    
            orgText = orgText.replace(pattern, function($1){
              return "<span style='background-color: red;'>" + $1 + "</span>"
            });
    
            $(str).html(orgText);
        });    
      });
    });​​
    

    link: http://jsbin.com/amica3/edit

    0 讨论(0)
  • 2020-12-19 13:26
    $('#myInputText').keypress(function(e) {
        switch (e.keyCode) {
            case 13: // "Enter" was pressed; handle it if you want
                return false;
    
            case 27: // ESC was pressed; handle it if you want
                return false;
        }
    
        $('body').highlight($(this).val());
    });
    
    0 讨论(0)
提交回复
热议问题