使字符串中的单个字母具有不同的颜色

Making individual letters in a string different colours

本文关键字:颜色 字符串 单个字      更新时间:2023-09-26

我正在尝试使字符串中某些字母(如果找到)的颜色不同,例如字母 i。搜索计数正在工作,我只是无法弄清楚单个字母的 html 颜色变化。

我知道如果它是一个完整的单词,那么我只能使用拆分字符串,但无法弄清楚如何为单个字母做到这一点。我找到了一些例子,我尝试过的一个在底部也不起作用。

//getMsg is another function, which passes in a user inputted string
function searchMsg(getMsg) { 
            alert (getMsg);
            var msgBoxObject = document.getElementById('msgBox');
            var pos = getMsg.indexOf('i')
            var txtToFind = (document.getElementById('txtToFind').value);
            var count = 0;
            while (pos !== -1){
                count++;
                pos = getMsg.indexOf('i', pos + 1);
                document.writeln (+count);
            msgBoxObject.innerHTML = (count);
        }
    getMsg = getMsg.replace('/i/g<span class="red">i</span>');
 document.writeln (getMsg);
}

 Edit; I've added in this, but can't get the loop to work correctly so it displays all instances of the letter found instead of just one: /*while (pos !== -1){
                count++;
                pos = getMsg.indexOf('i', pos + 1);
                document.writeln (+count);
            msgBoxObject.innerHTML = (count);
        }
        */

var count = 0;//目标值的计数 变量 i = 0; 迭代计数器

// Examine each element.
for(i=0; i<arr.length; i++) 
{   if(arr[i] == targetValue) 
        count++;
}
return count;
}
searchIndex = txtMsg.indexOf(txtToFind);
        if (searchIndex >=0 ) {
      // Copy text from phrase up till the match.
      matchPhrase = txtMsg.slice(0, searchIndex);
      matchPhrase += '<font color="red">' + txtToFind + '</font>';
      matchPhrase += txtMsg.slice(searchIndex + txtToFind.length);          
} else {
      matchPhrase = "No matches"
}
displayProcessedMsg(matchPhrase);

document.writeln(matchPhrase);

您需要为该类添加相应的 css 或更改标记,如指定的@john_Smith

添加 CSS

span.red {
  color: red;
}

更改标记

在您的代码上替换此

getMsg = getMsg.replace('/i/g<span class="red">i</span>');

getMsg = getMsg.replace('/i/g<span style:"color:red">i</span>');

内联 CSS 的一些示例

关于调色板的一些建议

尝试查看 d3 色阶(https://github.com/mbostock/d3/wiki/Ordinal-Scales#分类颜色)或应用类似于递增 RGB 值而不是使用颜色名称的原则。

希望这有帮助。