更改搜索栏中每个单词的背景颜色

时间:2016-04-04 15:45:35

标签: jquery html css search highlight

我一直在尝试用jQuery中的每个单词,并给它们一个彩色背景,我找到了一个解决方案,但它只适用于html内容,我想为搜索栏的输入着色。这是我发现的一个问题

HTML

some content
<div>another content 
    <input id="search" type="text" value="dsfdsfdsf sdf dsfsdfsfs">
</div>
<p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac turpis
</p>
content in body

的jQuery

//the main point here is you need to replace only the contents of the text node, not all the html parts

var colours = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'gray'];
var lastC;

jQuery('*').contents().each(function () {
    //not a text node or there is no content to replace
    if (this.nodeType != 3 || !this.nodeValue.trim()) {
        return;
    }

    //replace the value of the text node
    $(this).replaceWith(this.nodeValue.replace(/\w+/g, function (part) {
        var c = colours[Math.floor(Math.random() * colours.length)];
        while (c == lastC) {
            var c = colours[Math.floor(Math.random() * colours.length)];
        }
        lastC = c;
        return '<span style="background-color: '+c+';">' + part.split("").join("") + '</span>'
    }))
});

我尝试将jQuery('*')更改为jQuery('#search'),但它无效。

实例 https://jsfiddle.net/7hs9mgLp/2/

我应该怎么做才能解决它?

1 个答案:

答案 0 :(得分:1)

In fact, it cannot works with an text input element because this function get the content to englobe it in a span element and not the value of the element.

But I've made a fix to make it works with your code, with applying a random color on the background input element.

You can see it here

Here's the JS code :

//the main point here is you need to replace only the contents of the text node, not all the html parts

var colours = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'gray'];
var lastC;

jQuery('*').contents().each(function () {
    //not a text node or there is no content to replace
     // here is the part I've changed. I test what is the element we get
     if ( $(this).is( "input" ) ) {
        color = colours[Math.floor(Math.random() * colours.length)];
        $(this).css('background-color',color);
     }
    else{
      if (this.nodeType != 3 || !this.nodeValue.trim()) {
          return;
      }

      //replace the value of the text node
      $(this).replaceWith(this.nodeValue.replace(/\w+/g, function (part) {
          var c = colours[Math.floor(Math.random() * colours.length)];
          while (c == lastC) {
              var c = colours[Math.floor(Math.random() * colours.length)];
          }
          lastC = c;
          return '<span style="background-color: '+c+';">' + part.split("").join("") + '</span>'
      }));
    }
});

EDIT

To color each words in the input, it's kind of tricky and I don't know if there a "clean" way to do that.

Anyway, here's my suggestion for this part

See this updated fiddle

I've changed a little the HTML structure to do this because I can't figure out an other way to do it. Hope it helps.

Here's the JS part updated :

if ( $(this).is( "input" ) ) {
  val = $(this).val().split(" ");
  $( val ).each(function(i,v ) {
    color = colours[Math.floor(Math.random() * colours.length)];
    $("label").append("<span class='absolute' style='background-color: "+color+"; '>"+v+"</span>");
    $('#search').css('position','relative');
    $(this).val('');
    $('label').css({'position' : 'absolute', 'left' : '2px', 'top' : '2px' });
  });
}