在Javascript中为每个单词的第一个字母添加样式颜色是无效的



我试图在动态html元素中的每个单词的第一个字母上添加颜色。但是这种风格在我的Javascript代码中不起作用。

这是我的代码:https://jsfiddle.net/Devbuddy/1q9wcmbu/5/

<h1 id="heading">
The heading text here
</h1>
window.onload = (event) => {
const headingTxt = document.getElementById('heading').innerText;
const headingM = headingTxt.match(/b(w)/g);
const headingTxtJ = headingM.join('');
for(let i=0; i < headingTxtJ.length; i++){
headingTxtJ[i].style.color = 'red';
}
}

使用JS将第一个字母包装在span中并应用样式。

window.onload = (event) => {
const heading = document.getElementById('heading');
const headingTxt = heading.innerText;
const headingWords = headingTxt.split(/[ t]+/); //regex matches any number of spaces
heading.innerHTML = headingWords.map(word => {
const firstLetter = word.substring(0,1);
const restOfWord = word.substring(1,word.length);
return `<span style="color: red">${firstLetter}</span>${restOfWord}`
}).join(' ');
}
<h1 id="heading">
The heading    text    here
</h1>

您可以将标题文本split()转换为单词,然后在每个单词上使用substr()提取第一个字母并对其应用样式。

const headingTxt = document.getElementById('heading');
const words = headingTxt.innerText.split(' ')
let output = ''
for (let word of words) {
output += '<span style="color:red;">' + word.substr(0, 1) + '</span>' + word.substr(1, word.length) + ' '
}
headingTxt.innerHTML = output
<h1 id="heading">The heading text here</h1>

您可以使用regex replace来执行此操作。简化且更干净。

let str = document.getElementById("heading");
str.innerHTML = str.innerHTML.replace(/b(w)/g, "<span class='first-letter'>$1</span>")
.first-letter {
color: red;
}
<h1 id="heading">
The heading text here
</h1>

const colorizeLettersHtml = (str = '', color = '#ccc') => str.split(/ +/)
.map((word) => {
const [first, ...others] = word
return `<span style="color:${color}">${first}</span>${others.join('')}`
})
.join(' ')

和真正的DOM元素

const elementWithText = document.querySelector('#heading')
elementWithText.innerHTML = 
colorizeLettersHtml(elementWithText.textContent, '#f60')

最新更新