javascript - 如何更改单词中间字母的颜色(来自数组),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();
}
解决方案
这是更新的 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
}
希望这对你有用。
推荐阅读
- azure - Azure 数据湖分析是否支持 ADLS Gen2?
- python - 如何从两个版本中调用特定的 numpy
- markdown - Pandoc 丢失了从 docx 转换为 markdown 的标题和其他元数据
- javascript - 对于不支持承诺和/或异步等待的旧浏览器,如何等待回调运行?
- react-native - 在 react-native 中在哪里使用后台地理位置服务
- java - String str=null 和 String str="null" 有什么区别?
- kubernetes - kubectl 无法识别“dashboard/deployment.yml”
- vue.js - Vue SFC 为所有组件添加全局 Sass 变量
- mysql - MYSQL:在表中创建具有到期日期的行
- docker - Minikube - 访问主机的端口