简体   繁体   English

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

[英]How to highlight text in realtime with input?

I'm trying to highlight text in realtime using JQuery or Javascript. 我正在尝试使用JQuery或Javascript实时突出显示文本。 Current code doesn't want to search from .filters-no-actions block. 当前代码不想从.filters-no-actions块中搜索。

How it should look like: 它应该是什么样的:

在此处输入图片说明

Note: I don't want to add new text to the .filters-no-actions block, but only find text in this block using input value and highlight them. 注意:我不想将新文本添加到.filters-no-actions块,而仅使用输入值在此块中查找文本并突出显示它们。

CSS 的CSS

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

HTML 的HTML

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

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

Script 脚本

$(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>');
    }
  });

});

You need to use the keyup event instead of the change event. 您需要使用keyup事件而不是change事件。 Here is how you can do it: 这是您可以执行的操作:

 $(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> 

As Santu Roy said (+1 for him) you could try a jQuery highlight plugin like this: http://bartaz.github.io/sandbox.js/jquery.highlight.html . 正如Santu Roy所说(为他+1),您可以尝试这样的jQuery高亮插件: http : //bartaz.github.io/sandbox.js/jquery.highlight.html

In this exemple, I used it in a small delay function that is trigger after 100ms (you can change this time) your last keyup [thanks to Ata ul Mustafa for this solution: How to trigger an event in input text after I stop typing/writing? 在此示例中,我将其用在一个小的延迟函数中,该函数在最后一次键入 100ms(您可以更改一次)后触发(感谢Ata ul Mustafa提供此解决方案: 如何在我停止键入后触发输入文本中的事件/写作? +1 also for him]. 也为他+1)。

Try it: 试试吧:

 /* 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM