[英]How to Change Colors of a Text Randomly after a (,) split using jquery
i am trying to fix this problem but i am unable to solve it.. I am getting text from a database, a marquee text that scrolls, the point is, i want to change the color of text randomly just after each comma(,) separation... i am able to change the text on page load randomly but the whole text is changed. 我正在尝试解决这个问题,但我无法解决它..我从数据库获取文本,滚动的选框文本,重点是,我想在每个逗号(,)之后随机更改文本的颜色分离...我可以随意更改页面加载上的文本,但整个文本已更改。 I want to change text after the omma.. eg.
我想在omma之后更改文本。例如。 Hello , I am , Nick ,
你好 , 我是 , 尼克 ,
Now Hello Should be displayed in different color, and so on... 现在你好应该以不同的颜色显示,依此类推......
Here is my code, but it does all the text random color 这是我的代码,但它完成了所有文本的随机颜色
var colours = Array("yellow", "white", "green", "orange"), indexNo;
$('#header').each(function (index, character) {
indexNo = Math.floor(Math.random() * colours.length);
//alert(idx);
$('#header').css("color", colours[indexNo]);
});
}, function () {
$('#header', this).css("color", "#ddd");
});
$("#header").each
is not necessary since there is only one of those. $("#header").each
都没有必要,因为只有其中一个。 You can just use the string .split
method. 您可以使用字符串
.split
方法。
$("#header").html(function (_, html) {
return html.split(',').reduce(function (prev, cur) {
return prev + "<span style='color: " +
colours[Math.floor(Math.random() * colours.length)] + ";'>"
+ cur + "</span>";
}, '');
});
http://jsbin.com/abikin/1/edit http://jsbin.com/abikin/1/edit
EDIT: if the commas don't have to go inside of spans you can use this instead: 编辑:如果逗号不必进入跨度,你可以使用它:
return html.split(',').map(function (elem) {
return "<span" ... + elem + "</span>"
}).join(',');
http://jsbin.com/abikin/3/edit http://jsbin.com/abikin/3/edit
I just reworked Explosions a little because .reduce is for IE9 or above (I think). 我只是稍微改造了Explosions,因为.reduce适用于IE9或以上(我认为)。 I am sure he can do a more elegant version than the following... but worth a shot.
我相信他能做出比以下更优雅的版本...但值得一试。 Though this gives you all text are random, not sure that is what you want.
虽然这给你所有的文字是随机的,但不确定这是你想要的。 If not, sorry.
如果没有,抱歉。
var colours = Array("yellow", "black", "green", "orange","red","purple");
var newHtml = [];
$("#header").html(function (_, html) {
$.each(html.split(','),function (_,obj) {
newHtml.push("<span style='color: " + colours[Math.floor(Math.random() * colours.length)] + ";'>" + obj + "</span>");
});
return newHtml.join(',');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.