更改输入文本的颜色

时间:2017-09-14 19:39:38

标签: javascript html

我有一个文本框,我点击按钮后输入文字并在下面的段落中显示。但是我想要3的倍数显示不同的颜色,例如蓝色。

如果我输入我是蝙蝠侠。然后我想要m,t,n等等,将其涂成蓝色。 我该如何实现这一目标? 任何帮助表示赞赏。

以下是我尝试过的代码:

function change() {
  myOutput = document.getElementById('output');
  textbox = document.getElementById('text').value;
  myOutput.innerHTML = "You entered: " + textbox;
  var arr = textbox.split('');
  console.log(arr);
  for (i = 0; i < arr.length; i += 3) {
    console.log(i);
  }
}
<input type="text" id="text" />
<button onclick="change()">Change</button>
<p id="output"></p>

1 个答案:

答案 0 :(得分:2)

function change() {
  myOutput = document.getElementById('output');
  textbox = document.getElementById('text').value;
  
  var arr = textbox.split('');
  var newText = '';
  console.log(arr);
  for (i = 0; i < arr.length; i++) {
    if(i%3==2){
      newText += "<strong style='color:blue'>"+arr[i]+"</strong>";
    }else{
      newText += arr[i];
    }
  }
  myOutput.innerHTML = "You entered: " + newText;
}
<input type="text" id="text" />
<button onclick="change()">Change</button>
<p id="output"></p>

相关问题