2017-09-14 103 views
1

我有一个文本框,通过它我输入的文本,并在下面后,我点击一个按钮一个段落显示。但是我想要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>

回答

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>

+0

美丽。这工作。谢谢 – DragonBorn

+0

@SLASH这是我的荣幸:) – zynkn

+0

能否请你解释一下这段代码'if(i%3 == 2){' – DragonBorn