如何使用输入实时突出显示文本?

时间:2018-10-27 16:50:05

标签: javascript jquery

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

应如何显示:

enter image description here

注意:我不想将新文本添加到.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>');
    }
  });

});

2 个答案:

答案 0 :(得分:2)

您需要使用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>

答案 1 :(得分:1)

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

在此示例中,我将其用于一个小的延迟函数中,该函数在您上次键入100ms(您可以更改此时间)后触发[感谢 Ata ul Mustafa ,此解决方案:{{3 }}也为他+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>