【问题标题】:How to highlight text in realtime with input?如何通过输入实时突出显示文本?
【发布时间】:2019-04-01 03:03:33
【问题描述】:

我正在尝试使用 JQuery 或 Javascript 实时突出显示文本。当前代码不想从.filters-no-actions 块中搜索。

它应该是什么样子:

注意:我不想在.filters-no-actions 块中添加新文本,而只想使用输入值在该块中查找文本并突出显示它们。

CSS

.highlight_y {
  background-color: yellow;
}
p, div {
 display: inline-block;
}

HTML

<input id="ue__searchInput" placeholder="Search">

<div class="filters-no-actions">
  <p>Example text to search</p>
  <p>Lorem ipsum and...</p>
</div>

脚本

$(document).ready(function(){

  var search_input = $('#ue__searchInput');
  $(search_input).change(function(){
    var search_box = $('.filters-no-actions').text();
    var search_box_val = search_box.val();
    if (search_box_val == this.val()) {
      search_box.append('<div class="highlight_y">' + search_box_val + '</div>');
    }
  });

});

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    您需要使用 keyup 事件而不是 change 事件。以下是你可以做到的:

    $(document).ready(function(){
    
          var search_input = $('#ue__searchInput');
          $(document).on('keyup', '#ue__searchInput',function(){
            var search_box = $('.filters-no-actions').text();
            var search_box_val = search_input.val();
            if (search_input.val() != '') {
              $('.highlight_y').html('<p class="highlight_text">' + search_input.val() + '</p>');
            }
            else
            {
              $('.highlight_y').html('');
            }
          });
    
        });
    .highlight_y {
      background-color: yellow;
    }
    p, div {
     display: inline-block;
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
    
    </head>
    
    <body>
    
        
     <input id="ue__searchInput" placeholder="Search">
     <div class="highlight_y"></div>
      <div class="filters-no-actions">
        <p>Example text to search</p>
        <p>Lorem ipsum and...</p>
      </div>
    
    
    </body>
    
    </html>

    【讨论】:

    • 您的代码将新文本添加到 thix 框,这与我的问题无关。我的意思是根据输入值从框中查找文本并在此框中突出显示它们。
    • 好的,你可以看看jQuery高亮插件
    【解决方案2】:

    正如 Santu Roy 所说(为他 +1),您可以尝试这样的 jQuery 高亮插件:http://bartaz.github.io/sandbox.js/jquery.highlight.html

    在这个例子中,我在一个小的延迟函数中使用了它,该函数在 100 毫秒后触发(你可以更改这个时间)你的最后一次按键[感谢 Ata ul Mustafa 为这个解决方案:How to trigger an event in input text after I stop typing/writing? +1 也为他]。

    试试看:

    /* This is the plugin. Put it in an external file 
    => https://github.com/bartaz/sandbox.js/blob/master/jquery.highlight.js
    
    Here you can find all the documentation: http://bartaz.github.io/sandbox.js/jquery.highlight.html
    
    */
    
    jQuery.extend({
        highlight: function (node, re, nodeName, className) {
            if (node.nodeType === 3) {
                var match = node.data.match(re);
                if (match) {
                    var highlight = document.createElement(nodeName || 'span');
                    highlight.className = className || 'highlight';
                    var wordNode = node.splitText(match.index);
                    wordNode.splitText(match[0].length);
                    var wordClone = wordNode.cloneNode(true);
                    highlight.appendChild(wordClone);
                    wordNode.parentNode.replaceChild(highlight, wordNode);
                    return 1; //skip added node in parent
                }
            } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
                    !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
                    !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
                for (var i = 0; i < node.childNodes.length; i++) {
                    i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
                }
            }
            return 0;
        }
    });
    
    jQuery.fn.unhighlight = function (options) {
        var settings = { className: 'highlight', element: 'span' };
        jQuery.extend(settings, options);
    
        return this.find(settings.element + "." + settings.className).each(function () {
            var parent = this.parentNode;
            parent.replaceChild(this.firstChild, this);
            parent.normalize();
        }).end();
    };
    
    jQuery.fn.highlight = function (words, options) {
        var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
        jQuery.extend(settings, options);
        
        if (words.constructor === String) {
            words = [words];
        }
        words = jQuery.grep(words, function(word, i){
          return word != '';
        });
        words = jQuery.map(words, function(word, i) {
          return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
        });
        if (words.length == 0) { return this; };
    
        var flag = settings.caseSensitive ? "" : "i";
        var pattern = "(" + words.join("|") + ")";
        if (settings.wordsOnly) {
            pattern = "\\b" + pattern + "\\b";
        }
        var re = new RegExp(pattern, flag);
        
        return this.each(function () {
            jQuery.highlight(this, re, settings.element, settings.className);
        });
    };
    
    
    
    
    
    
    
    
    
    
    
    
    $(document).ready(function(){
      var delay = (function(){
        var timer = 0;
        return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
       };
      })();
    
      var search_input = $('#ue__searchInput');
    
      $(search_input).on('keyup',function(){
    
        delay(function(){
            $(".filters-no-actions").unhighlight({ className: 'highlight_y'}); /*remove all highlight before create a new one */
            $(".filters-no-actions").highlight($(search_input).val(), { className: 'highlight_y'});
        }, 100 );
      });
    
    });
    .highlight_y {
        background-color: #FFFF88;
    }
    p, div {
     display: inline-block;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input id="ue__searchInput" placeholder="Search">
    <div class="highlight_y"></div>
    <div class="filters-no-actions">
      <p>Example text to search</p>
      <p>Lorem ipsum and...</p>
    </div>

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 2014-04-03
      • 2012-08-21
      • 1970-01-01
      相关资源
      最近更新 更多