【发布时间】:2016-07-24 06:18:17
【问题描述】:
我一直在尝试对 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/
我该怎么做才能解决它?
【问题讨论】:
标签: jquery html css search highlight