随机彩色字母 [英] Random Colorful letters

查看:29
本文介绍了随机彩色字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

<div  id="list" rows="10"></div>
<script>
 $(function() {
   setTime();
   function setTime() {
       $.ajax({
            url : "../abc.php",
            dataType: "text",
            success : function (result) {
                $("#list").html(result);
            }           
        });
      var date = new Date().getTime();
      setTimeout(setTime, 3000);
      $('#list').html(result);
      //Here  should call a function to color all the words of the div
   }


    });
</script>

    });

我正在尝试使用 setTime () 函数每 3 秒为所有字母着色.

I'm trying to color all letters every 3 seconds using the setTime () function.

注意:我正在尝试为单词的每个字母着色,换句话说,每个字母都会有颜色

Note: I'm trying to color each letter of a word, in other words, each letter will have a color

喜欢:

https://i.imgur.com/Tw2Q58U.png

我试过这段代码,但它改变了整个 div 的颜色(div 只保留一种颜色):

I tried with this code, but it changes the color of the entire div(The div stay with only one color):

var randomColor = Math.floor(Math.random()*16777215).toString(16);
document.getElementById('list').style.color = '#' + randomColor

推荐答案

如果结果是一个文本,那么你需要用 span 包裹每个字母..喜欢下面的代码:

If result is a text then you need to wrap each letter with span.. do like code below:

<div  id="list" rows="10"></div>
<script>
  $(function() {
    setTime();
    function setTime() {
        $.ajax({
             url : "../abc.php",
             dataType: "text",
             success : function (result) {
                  $("#list").html(result);
                  $("#list")
                  .contents()
                  .filter(function(){
                    return this.nodeType !== 1;
                  })
                  .wrap( "<b class='colorful_text'></b>" );
                   $.each($(".colorful_text"), function(o, v){

                      var textEle = $(this).text()
                      console.log("textEle", textEle)
                      $(this).html("")
                      for(var n=0; n<textEle.length; n++) {
                            var randomColor = Math.floor(Math.random()*16777215).toString(16);
                            var color = '#' + randomColor
                            var ele = document.createElement("span")
                            ele.style.color = color
                            ele.innerText = textEle[n]        

                            $(this).append(ele)

                      }

                })
             }           
        });
       var date = new Date().getTime();
       setTimeout(setTime, 3000);
       $("#list").html();

       //Here  should call a function to color all the words of the div
    }

});
</script>

这篇关于随机彩色字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆