【问题标题】:jQuery plugin - highlight textjQuery 插件 - 突出显示文本
【发布时间】:2016-01-24 01:08:22
【问题描述】:

我正在创建一个 jQuery 插件。它接受用户输入,并应突出显示现有页面内容中的文本。现在,该插件正在突出显示包含用户输入内容的整行。

理想情况下,它只匹配输入的短语。

我有三个文件:

HTML 文件:

<input type="text" id="name">
<p>harry gambhir is sitting in oakville tim hortons drinking coffe </p>

插件文件:

$(document).ready(function(){
(function ( $ ) {
$.fn.high = function(){
    $("#name").keyup(function(){
        var user = $(this).val();
        var hhh = $("p:contains('"+ user + "')").addClass('highlight');

    });
};
}(jQuery));
$('p').high();
});

CSS 文件:

.highlight{

    background-color:#000000;

}

也许我需要在字母表周围创建一个跨度标签,然后添加类以突出显示它。我不知道如何将跨度标签分配给输入的文本。这只是一个想法,如果有更好的解决方案,请告诉我。

【问题讨论】:

  • 这确实很常见,并且已经有一些组件,例如mark.js.

标签: javascript jquery html css plugins


【解决方案1】:

尝试使用.html().text()String.prototype.replace(),将p元素的原始html保存为变量以重置p元素html如果.val()返回空字符串

$(document).ready(function() {
  (function($) {
    // pass element selector to `.high()` 
    $.fn.high = function(elem) {
      // cache `this` element
      el = this;
      // save original `html` of `el`
      originalHTML = el.html();
      $(elem).keyup(function() {
        var user = $(this).val();
        // if `user` is not empty string
        if (user.length) {
          el.html(function(_, html) {
            return el.text()
                  .replace(new RegExp("(" 
                    + user.trim().split("").join("|") 
                    + ")"
                  , "g")
                   // replace matched character with `span` element
                   // add `highlight` `class` to `span` element
                   , "<span class=highlight>$1</span>")
          })
        } else {
          // reset `p` : `el` `html` to `originalHTML`
          el.html(originalHTML)
        }

      });
    };
  }(jQuery));
  $("p").high("#name"); // pass `#name` as selector to `.high()`
});
.highlight {
  color: yellow;
  background-color: #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" id="name">
<p>harry gambhir is sitting in oakville tim hortons drinking coffe</p>

【讨论】:

  • 这将破坏 DOM 事件,因为它在后台使用 innerHTML
猜你喜欢
  • 1970-01-01
  • 2011-02-08
  • 2011-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多