Javascript - 如何设置文本字符串中特定单词的样式?

我这里有一个文本字符串,它将动态生成为以下之一:

<h1 id="headline">"Get your FREE toothbrush!"</h1>

OR

<h1 id="headline">"FREE floss set and dentures!"</h1>

由于这将是动态生成的,我无法将<span>“FREE”一词包裹起来,因此我想使用 Javascript 专门针对“FREE”一词,以便我可以使用不同的字体系列和字体颜色对其进行样式设置比<h1>设置的任何样式都重要。我使用什么方法来做到这一点?


尚方宝剑之说
浏览 179回答 4
4回答

阿波罗的战车

您可以搜索子字符串“FREE”并将其替换为样式化 HTML。如果“FREE”在字符串中出现多次,您可能需要使用正则表达式(除非您不需要支持 Internet Explorer)。在你的情况下:let str = '<h1 id="headline">"FREE floss set and dentures!"</h1>' str = str.replace(/FREE/g, '<span color="red">FREE</span>');

白猪掌柜的

这是一个使用切片和一些经典串联的工作示例。编辑:现在还包括第二个字符串的代码。//get headline by idvar headline = document.getElementById("headline");//declare your possible strings in varsvar string1 = "Get your FREE toothbrush!"var string2 = "FREE floss set and dentures!"//declare formatted span with "FREE" in varvar formattedFree = "<span style='color: blue; font-style: italic;'>FREE</span>"//target positions for the rest of your stringvar string1Position = 13var string2Position = 4//concat your vars into expected positions for each stringvar newString1 = string1.slice(0, 9) + formattedFree + string1.slice(string1Position);var newString2 = formattedFree + string2.slice(string2Position)//check if strings exist in html, if they do then append the new strings with formatted spanif (headline.innerHTML.includes(string1)) {&nbsp; headline.innerHTML = newString1&nbsp;}else if (headline.innerHTML.includes(string2)) {&nbsp; headline.innerHTML = newString2}<!-- As you can see the original string does not have "FREE" formatted --><!-- Change this to your other string "FREE floss set and dentures!" to see it work there as well --><h1 id="headline">Get your FREE toothbrush!</h1>

大话西游666

您要查找的属性是innerHTML,请查看以下示例:var word = document.getElementById('word');function changeWord(){&nbsp; &nbsp; word.innerHTML = "another";&nbsp; word.style.backgroundColor = 'black';&nbsp; word.style.color = 'white';}<h1 id="headline">&nbsp; <span id="word">some</span> base title</h1><button onClick="changeWord()">&nbsp; change</button>

蝴蝶刀刀

您可以拆分文本并将关键字“FREE”转换为 span 元素。因此您可以设置关键字“FREE”的样式。此方法是安全的,因为不会更改任何非文本 html 元素。var keyword = "FREE";var headline = document.getElementById("headline");var highlight, index;headline.childNodes.forEach(child => {&nbsp; if (child.nodeType == Node.TEXT_NODE) {&nbsp; &nbsp; while ((index = child.textContent.indexOf(keyword)) != -1) {&nbsp; &nbsp; &nbsp; highlight = child.splitText(index);&nbsp; &nbsp; &nbsp; child = highlight.splitText(keyword.length);&nbsp; &nbsp; &nbsp; with(headline.insertBefore(document.createElement("span"), highlight)) {&nbsp; &nbsp; &nbsp; &nbsp; appendChild(highlight);&nbsp; &nbsp; &nbsp; &nbsp; className = 'highlight';&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }});.highlight {&nbsp; /* style your keyword */&nbsp; background-color: yellow;}<div id="FREE">&nbsp; <h1 id="headline">"Get your FREE toothbrush! FREE floss set and dentures!"</h1></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript