如何更改单词中间字母的颜色(来自数组),javascript

我不知道返回修改中间字母颜色的单词的正确结构。我使用拆分将段落中的所有单词保存在一个数组中,但是我必须修改每个单词,并用红色的中间字母显示它们。调查,我想我可以使用slice方法来修改字体颜色。这是我的代码:

HTML

  <body>
    <textarea id="text">JavaScript is the Programming Language for the Web,JavaScript can update and change both HTML and CSS,JavaScript can calculate,manipulate and validate data</textarea>
    <div class="show">
      <h3 id="txt"></h3>
    </div>
    <div class="control-box">
      <button type="button" name="button" onclick="iniciar()">play</button>
    </div>
  </body>
</html>

脚本

function iniciar(){
  var texto = document.getElementById("text").value;
  var palabras = texto.split(/[,]+/);
  var index = 0;
  console.log(palabras);

  function tester(){
    document.getElementById("txt").innerHTML=palabras[index];    
    var timer = setTimeout(function(){
      console.log(timer);
      tester();
    },550);

    console.log(palabras[index]);

    if (index>palabras.length-2){
        clearTimeout(timer);
    }
    index++;
  }
  tester();
}
xf_520 回答:如何更改单词中间字母的颜色(来自数组),javascript

这是更新的Javascript代码,返回数组中的每个单词,中间的字母为红色。

function iniciar(){
    var texto = document.getElementById("text").value;
    var updatedtexto = texto;
    var palabras = texto.split(/[,]+/);
    console.log(palabras);
    palabras.forEach(function(value,index){
        var wordstr = value;
        var wordLength = value.length; //get length of word
        var centerOfWord = (wordLength/2).toFixed(0); //get centerofword
        var middleLetter = wordstr.substring(parseInt(centerOfWord) - 1,parseInt(centerOfWord)); //get middle letter of word
        var colorWord = wordstr.replace(middleLetter,"<span style='color:red'>"+ middleLetter +"</span>"); //make middle letter color red
        setTimeout(function(){  //remove complete setTimeout if you want show full string with colored letters
            console.log(colorWord);
            document.getElementById("txt").innerHTML= colorWord; //show word
        },550*index);

        //updatedtexto = updatedtexto.replace(wordstr,colorWord);  //uncomment if you want show full string with colored letters
    });

    //document.getElementById("txt").innerHTML= updatedtexto; //uncomment if you want show full string with colored letters
}

希望这对您有用。

本文链接:https://www.f2er.com/3084078.html

大家都在问