[英]How to make each letter in text a different random color in Javascript
I am trying to make every letter in a small line of text a different random color. 我正在尝试使一小段文字中的每个字母使用不同的随机颜色。 I can only seem to make it do this when I use .hover, but I want it to do the action straight away (once the page loads). 当我使用.hover时,似乎只能使其执行此操作,但是我希望它立即执行操作(一旦页面加载)。 Please help. 请帮忙。 I would also like to know if anyone knows how to just set different colors on each letter (set colors) with css or Javascript because when I tried to do it in that way, it wouldnt allow me call a function on the same div/id (i tried to arch the text). 我也想知道是否有人知道如何使用CSS或Javascript在每个字母上设置不同的颜色(设置颜色),因为当我尝试以这种方式进行设置时,它不允许我在相同的div / id上调用函数(我试图把文本拱起来)。 Thank you. 谢谢。
THIS IS MY CODE 这是我的密码
var colours = ["#000000", "#FF0000", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"],
idx;
$("#arch").hover(function(){
var div = $(this);
var chars = div.text().split('');
div.html('');
for(var i=0; i<chars.length; i++) {
idx = Math.floor(Math.random() * colours.length);
var span = $('<span>' + chars[i] + '</span>').css("color", colours[idx])
div.append(span);
}
}, function() {
$(this).find('span').css("color","#FF0000");
});
var colours = ["#000000", "#FF0000", "#990066", "#FF9966", "#996666", "#00FF00", "#CC9933"],
idx;
$(function() {
var div = $('#arch');
var chars = div.text().split('');
div.html('');
for(var i=0; i<chars.length; i++) {
idx = Math.floor(Math.random() * colours.length);
var span = $('<span>' + chars[i] + '</span>').css("color", colours[idx]);
div.append(span);
}
});
Works for me. 为我工作。 jsFiddle jsFiddle
You have to make sure the DOM is loaded before doing any jQuery stuff on it. 您必须先对DOM进行加载,然后再对其执行任何jQuery处理。
http://learn.jquery.com/using-jquery-core/document-ready/ http://learn.jquery.com/using-jquery-core/document-ready/
Try (untested): 尝试(未试用):
$(document).ready(function(){
var div = $('#arch');
var chars = div.text().split('');
div.html('');
for(var i=0; i<chars.length; i++) {
idx = Math.floor(Math.random() * colours.length);
var span = $('<span>' + chars[i] + '</span>').css("color", colours[idx])
div.append(span);
}
}
Basically, you need to wait for the DOM to load so that there's a div to find when you call $('#arch')
! 基本上,您需要等待DOM加载,以便在调用$('#arch')
时找到一个div!
I'm not sure what you mean by "tried to arch the text". 我不确定“尝试使文本拱形”是什么意思。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.