Javascript 选择i进行颜色更改
我有一个小脚本,可以根据输入的长度改变背景和输入文本的颜色。我想做一个改变,但我不知道具体怎么做。我不想改变整个输入文本的颜色,我只想改变改变颜色的字母。所以字母一个接一个地改变颜色。下面是我的代码行,它调用的元素是“ids”。我需要说“ins[I]”之类的话,但我不知道具体是怎么说的Javascript 选择i进行颜色更改,javascript,for-loop,Javascript,For Loop,我有一个小脚本,可以根据输入的长度改变背景和输入文本的颜色。我想做一个改变,但我不知道具体怎么做。我不想改变整个输入文本的颜色,我只想改变改变颜色的字母。所以字母一个接一个地改变颜色。下面是我的代码行,它调用的元素是“ids”。我需要说“ins[I]”之类的话,但我不知道具体是怎么说的 我将感谢任何帮助。谢谢。样式化应用于HTML元素-字母不是HTML元素,因此您不能像您想象的那样以直接的方式进行。试试像这样的东西 <span id="letter0">T</span>&
我将感谢任何帮助。谢谢。样式化应用于HTML元素-字母不是HTML元素,因此您不能像您想象的那样以直接的方式进行。试试像这样的东西
<span id="letter0">T</span><span id="letter1">E</span><span id="letter2">S</span><span id="letter3">T</span>
测试
然后将样式应用于
span
元素。在一个简单的输入中不能有不同的多色字母,但可以使用HTML5 contenteditable属性和每个字母的span容器来构建它
此示例使用jQuery:
// we have a hidden input field and a div container for our coloured letters.
// we change the colours when the hidden input looses focus (blur event)
$("div").prop("contentEditable", true).blur(function(){
// get text from the div
var divText = $(this);
//and split to an array
var chars = divText.split("");
// set text as input field value
$("#hidden").val(divText);
// clear the div container
$(this).html("");
// generate a span for each letter from chars array, colour it and append to the div
$.each(chars, function(){
$("<span>").text(this).css({
color: "#"+(Math.random()*16777215|0).toString(16)
}).appendTo("div");
});
});
//我们有一个隐藏的输入字段和一个用于彩色字母的div容器。
//当隐藏的输入失去焦点时,我们改变颜色(模糊事件)
$(“div”).prop(“contentEditable”,true).blur(函数(){
//从div获取文本
var divText=$(此);
//并拆分为一个数组
var chars=divText.split(“”);
//将文本设置为输入字段值
$(“#隐藏”).val(divText);
//清除div容器
$(this.html(“”);
//为chars数组中的每个字母生成一个span,将其着色并附加到div
$.each(字符,函数(){
$(“”).文本(this).css({
颜色:#“+(Math.random()*16777215 | 0).toString(16)
}).附录(“div”);
});
});
这一点在本JSFIDLE中显示出来如果可以的话,为OP提供一个普通的解决方案将是有益的。或者至少描述一下你写的代码是怎么做的,这样他/她就可以按自己的。
// we have a hidden input field and a div container for our coloured letters.
// we change the colours when the hidden input looses focus (blur event)
$("div").prop("contentEditable", true).blur(function(){
// get text from the div
var divText = $(this);
//and split to an array
var chars = divText.split("");
// set text as input field value
$("#hidden").val(divText);
// clear the div container
$(this).html("");
// generate a span for each letter from chars array, colour it and append to the div
$.each(chars, function(){
$("<span>").text(this).css({
color: "#"+(Math.random()*16777215|0).toString(16)
}).appendTo("div");
});
});