首页 > 解决方案 > 如何更改单词中间字母的颜色(来自数组),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();
}

标签: javascriptarrayssplitslice

解决方案


这是更新的 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
}

希望这对你有用。


推荐阅读