0
我一直在试图抛出jQuery中的每个单词并给它们一个彩色背景,我找到了一个解决方案,但它只适用于html内容,我想为输入着色为搜索栏。而本作什么的examble我发现更改搜索栏中每个单词的背景颜色
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/
我应该这样做修复它?
谢谢你,你给我说说解决方案的想法,但我不想整个页面进行着色我想在搜索栏中每个单词有一个不同的背景颜色不像整个背景那样。谢谢 –
喜欢这个http://s9.postimg.org/t6qp02vin/dsfsfdsfdsfdsf.png –
这样做有点棘手,但我找到了一种可能的方式来获得你想要的结果。我已经更新了我的答案。 –