jQuery div元素中的每个字母,悬停时数组中的随机颜色 [英] jQuery each letter in div element, random colour from array on hover
问题描述
我试图让div元素中的每个字母从颜色数组变为随机颜色。然后当鼠标离开div时重置。
I'm trying to get each letter in a div element to change to a random colour from an array of colours. Then reset when the mouse moves off the div.
这是我到目前为止所得到的。我觉得我很接近,除了它实际上没有用的事实。这是由本网站上的几个不同的片段构建的。
Here's what I've got so far. I think I'm pretty close, apart from the fact it doesn't actually work. This was built from a few different snippets on this site.
$(document).ready(function() {
// COLOURS ARRAY
var colours = Array("#ddd", "#333", "#999", "#bbb"), idx;
$("DIV#header").hover(function(){
$( $(this).text().split('')).each(function(index, character) {
idx = Math.floor(Math.random() * colours.length);
$(this).css("color", colours[idx]);
});
}, function() {
$(this).css("color","#ddd");
});
});
它不会产生任何JS错误。悬停的第二个功能似乎有效但不是第一个。感谢任何帮助!
It doesn't produce any JS errors. The 2nd function of the hover seems to work but not the first. Any help would be gratefully received!
推荐答案
字符串不是元素,您不能为其添加CSS属性。你可以把你的字母放在span元素中然后设置样式,试试这个:
A string is not an element and you cannot add a CSS property to it. You can put your letters in span elements and then style them, try this:
$(document).ready(function() {
// COLOURS ARRAY
var colours = Array("#ddd", "#333", "#999", "#bbb"), idx;
$('DIV#header').hover(function(){
$('span', this).each(function(index, character) {
idx = Math.floor(Math.random() * colours.length);
$(this).css("color", colours[idx]);
});
}, function() {
$('span',this).css("color","#ddd");
});
});
这篇关于jQuery div元素中的每个字母,悬停时数组中的随机颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!