【问题标题】:How to change the color of the middle letter of a word (from an array), javascript如何更改单词中间字母的颜色(来自数组),javascript
【发布时间】:2020-03-13 08:42:35
【问题描述】:

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

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();
}

【问题讨论】:

  • 我强烈建议你学习缩进和结构化你的代码。
  • 你能告诉我在哪里吗?也许我没有注意到
  • 我也尝试格式化你的代码,但是你在另一个内部创建了一个函数并调用了内部......你的编码风格真的很奇怪。再次,请构建您的代码。
  • 到处,我不明白你的大部分代码。就像测试人员用超时调用自己一样,为什么?另一个里面的函数,为什么?
  • 如您所见,我有点新意 :/ 。所以我将一个函数放在另一个函数中,因为我只想在单击它后立即执行其他函数,我想有更好的方法来做到这一点。

标签: javascript arrays split slice


【解决方案1】:

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

希望这对你有用。

【讨论】:

  • 这不会更新实际的文本区域,我猜这是不可能的。
  • 不,只是返回到达词。
  • 同意使用 HTML 标签更新实际的 Textarea(span 即用于更新字母的颜色)不是一个好主意。
  • 代码已更新,可用于显示完整更新的字符串而不是每个单词。
  • 这比我的原始代码要好,非常感谢您的回答。没想过用substring方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-28
  • 2018-09-22
  • 1970-01-01
  • 2014-11-26
  • 2023-04-02
  • 2019-03-12
  • 1970-01-01
相关资源
最近更新 更多