Color every character differently

后端 未结 3 922
旧时难觅i
旧时难觅i 2020-12-19 13:30

I am using KK Countdown to countdown to Xmas for a site.

I have a design which I have to follow that has each letter of the day countown with a blue background and b

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-19 14:13

    I want to add a background colour to each letter inside that span.

    Using an array of colors:

    const colors = ["#0bf", "#f0b", "#fb0", "#b0f"];
    
    $('.kkc').find('span').each(function() {
    
      const text = $(this).text();
      const len = text.length;
        
      const newCont = [...text].reduce((a, ch, i) => 
        a + `${ch}`, ""
      );
    
      $(this).html(newCont);
    
    });
    .kkcountdown-box>span>span {
      background: red;
    }
    169 DAYS 23 19 48 HOURS

    The above will, wrapping every single letter into a separate span will also add a background color from your Array list of colors.
    Once the colors list end is reached will start from the first one and so on.

    Using a random color:

    $('.kkc').find('span').each(function() {
    
      const text = $(this).text();
      const len = text.length;
        
      const newCont = [...text].reduce((a, ch, i) => {
        const color= '#'+ (Math.random() * 0xffffff).toString(16).substr(-6); 
        return a + `${ch}`
      }, "");
    
      $(this).html(newCont);
    
    });
    .kkcountdown-box>span>span {
      background: red;
    }
    169 DAYS 23 19 48 HOURS

    The above will get every letter inside a and wrap it into a new span with a randomly generated background color.

提交回复
热议问题