正如其他人指出的那样,您只能对元素进行样式设置,因此您需要将每个字母包装在它自己的元素中。这是执行此操作的示例方法。它也以递归方式工作,因此这将适用于包含其他元素的文本,如<b>
、<a>
等。下面的其他示例假设该 div 将只有文本,没有其他 HTML 标记。
var colours = Array("#ddd", "#333", "#999", "#bbb");
$('#header').hover(function(){
wrapLetters(this);
$('.random-color', this).css('color', function(){
var idx = Math.floor(Math.random() * colours.length);
return colours[idx];
});
}, function(){
$('.random-color', this).css('color', '#ddd');
});
// Wrap every letter in a <span> with .random-color class.
function wrapLetters(el){
if ($(el).hasClass('random-color')) return;
// Go through children, need to make it an array because we modify
// childNodes inside the loop and things get confused by that.
$.each($.makeArray(el.childNodes), function(i, node){
// Recursively wrap things that aren't text.
if (node.nodeType !== Node.TEXT_NODE) return wrapLetters(node);
// Create new spans for every letter.
$.each(node.data, function(j, letter){
var span = $('<span class="random-color">').text(letter);
node.parentElement.insertBefore(span[0], node);
});
// Remove old non-wrapped text.
node.parentElement.removeChild(node);
});
}
小提琴:http: //jsfiddle.net/aWE9U/2/