2013-08-27 68 views
0

我正在嘗試創建一個Javascript函數,它隨機將字符串中的字符分配給我選擇的一組顏色。我不太知道如何在字符串中選擇一個角色,併爲其分配一個顏色顯示帶顏色的字符

這裏是我的代碼:

<script> 
     function Rainbow(x,chosencolor) { 
      var mystring = String(x);            @* convert to string*@ 
      var Stringlength = mystring.lenth;          @* length fo string *@ 
      var rainbowstring = new Array(Stringlength);       @* create array of appropriate size*@ 
      var counter = 0; 

      while (counter < Stringlength) { 
       var randomnumber = Math.floor(Math.random() * 10);      @* random number generator --> 11 means 0-10 *@   

        switch (randomnumber) { 
        case 0: 

         break; 
        case 1: 

         break; 
        case 2: 

         break; 
        case 3: 

         break; 
        case 4: 

         break; 
        case 5: 

         break; 
        case 6: 

         break; 
        case 7: 

         break; 
        case 8: 

         break; 
        case 9: 

         break; 
       } 
       rainbowstring[counter] = chosencolor;        @* assign color *@ 
       counter++;               @* increment *@ 
      } 
    } 

     @* need something that generates colors *@ 
     @* assigns colors to text *@ 

    </script> 

回答

1

試試這個:

<script> 
function Rainbow(x,chosencolor) { 
    var mystring = String(x);            @* convert to string*@ 
var Stringlength = mystring.lenth;          @* length fo string *@ 
var rainbowstring = new Array(Stringlength);       @* create array of appropriate size*@ 
var counter = 0; 
var clr, ltr; 
    while (counter < Stringlength) { 
    var randomnumber = Math.floor(Math.random() * 10);      @* random number generator --> 11 means 0-10 *@ 
    ltr = mystring.charAt(counter); //--- get the current letter  
    switch (randomnumber) { 
     case 0: clr='#f00'; break; 
     case 1: clr='#0f0'; break; 
     case 2: clr='#00f'; break; 
     case 3: clr='#000'; break; 
     case 4: clr='#fff'; break; 
     case 5: break; 
     case 6: break; 
     case 7: break; 
     case 8: break; 
     case 9: break; 
    } 
    rainbowstring[counter] = "<span style='color:"+clr+"'>"+ltr+"</span>";        @* assign color *@ 
    counter++;               @* increment *@ 
    } 
} 
</script>