如何更改其他字母的字体颜色? [英] How to change every other letter's font color?
问题描述
我正在尝试在论坛上创建一个圣诞节用户组,并希望使用JavaScript将用户名替换为绿色/红色图案.因此,基本上,JavaScript会将特定CSS类中的所有其他字母变成绿色,而其他字母保持红色.
I'm trying to create a Christmas user group on my forums, and would like to replace the users name with a green/red pattern using JavaScript. So basically, JavaScript would turn every other letter within a specific CSS class into green, and the others would stay red.
这就是现在的样子:
<span class="style6">Username</span>
我希望JavaScript将其转换为如下形式:
I'd like JavaScript to turn it into something like this:
<span class="style6">
<span class="color_red">U</span>
<span class="color_green">s</span>
<span class="color_red">e</span>
<span class="color_green">r</span>
<span class="color_red">n</span>
<span class="color_green">a</span>
<span class="color_red">m</span>
<span class="color_green">e</span>
</span>
推荐答案
只要您的< span>
不包含任何HTML,您就可以执行此操作.
As long as your <span>
doesn't contain any HTML you could do this.
$('.style6').each(function(){
var letters = $(this).text().split('');
$(this).text('');
for(var i = 0; i < letters.length; i++){
if(i % 2 == 0){
$(this).append('<span class="color_red">' + letters[i] + '</span>');
}
else{
$(this).append('<span class="color_green">' + letters[i] + '</span>');
}
}
});
如果您的< span>
确实包含HMTL,将会更加复杂.
It would be a bit more complicated if your <span>
did contain HMTL.
这是与jQuery BTW一起使用的.不确定是否可以.
This is with jQuery BTW. Not sure if that is OK.
这篇关于如何更改其他字母的字体颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!