如何选择页面中的每个单词,反转它并给它另一种颜色?
我现在尝试的是:
jQuery('*').each(function(){
var text = jQuery(this).text().split(' '),
len = text.length,
result = [];
for( var i = 0; i < len; i++ ) {
result[i] = '<span style="color: green;">' + text[i].split("").reverse().join("") + '</span>';
}
jQuery(this).html(result.join(' '));
});
但我离我需要的还很远。 有线索吗?
答案 0 :(得分:1)
您正在尝试替换元素的全部内容,当您尝试替换根节点时出现问题
//the main point here is you need to replace only the contents of the text node, not all the html parts
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) {
return '<span style="color: green;">' + part.split("").reverse().join("") + '</span>'
}))
});
演示:Fiddle
答案 1 :(得分:1)
这会将文本拆分为单词(基于空格,但如果你想要更复杂的东西,你可以使用正则表达式),然后reverses the word,为每个单词指定一个颜色并将其写入结果div
。
var main = document.getElementById('main');
var result = document.getElementById('result');
var text = main.textContent;
var words = text.split(' ');
var colours = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'black'];
for(var wi = 0; wi < words.length; wi++)
{
if(words[wi] !== '')
{
var c = colours[Math.floor(Math.random() * colours.length)];
result.innerHTML += '<span class="'+c+'">'+words[wi].split("").reverse().join("")+'</span> ';
}
}
span.red
{
color:#ff0000;
}
span.green
{
color:#00ff00;
}
span.blue
{
color:#0000ff;
}
span.cyan
{
color:#00ffff;
}
span.magenta
{
color:#ff00ff;
}
span.yellow
{
color:#ffff00;
}
span.black
{
color:#000000;
}
<div id="main">
There is a bunch of words here. Maybe we can split them up and change their colours.
</div>
<div id="result">
</div>