javaScript对字符串中的每个字符进行着色

时间:2014-12-01 15:56:31

标签: javascript

您好我正在使用javascript和jquery,我正在尝试将日期方法(例如d.getMonth())连接到字符串中,以便稍后我可以浏览每个字符并使用jquery更改颜色。

<script type = "text/javascript">

    var d = new Date();


        $("document").ready(function(){ //$ is jquerys way of selecting a dom element

            $("#one").append(d.getMonth() + "/" + d.getDay() + "/" + d.getFullYear()
            + "/" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());

            var myTextDate = $("#one").text();
            for (var i = 17; i < myTextDate.length; i++)
            {





            }
        });

            //$("span").css("background-color","black");
            function getRandomColor() 
            {
                var letters = '0123456789ABCDEF'.split('');
                var color = '#';
                for (var i = 0; i < 6; i++ ) {
                    color += letters[Math.floor(Math.random() * 16)];
            }
                return color;
            }

    </script>

    <h3 id = "one">Today's Date is: </h3>

这是我的原始代码。我尝试将它们附加到有效的html文档中。然后我做了一个生成随机颜色的方法。现在我想改变每个角色的颜色。但是将每个特征改变为不同的颜色是我失败的地方。

1 个答案:

答案 0 :(得分:0)

如果要更改每个字符的颜色,则必须将每个字符包装在其自己的元素中。您可以使用<span> s解决它:

var string = "My String";
var result = "";
/* Let's run through each letter and wrap it in a span. */
for(var i = 0; i < string.length; i++){
    var color = getRandomColor();
    result += '<span style="color: ' + color + '">' + string[i] + '</span>';
}
/* Now write it to the document. It might be safer to add it to an existing ID as innerHTML
   because you might want to have control over this huge list of elements. */
document.write(result);

但是当字符串变得很长时,这不是很好的表现。

getRandomColor()函数有一点改进:

function getRandomColor() 
{
    /* You don't need to split, as strings are already arrays (of characters, that is) */
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}