4 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以搜索子字符串“FREE”并將其替換為樣式化 HTML。如果“FREE”在字符串中出現(xiàn)多次,您可能需要使用正則表達(dá)式(除非您不需要支持 Internet Explorer)。
在你的情況下:
let?str?=?'<h1?id="headline">"FREE?floss?set?and?dentures!"</h1>' str?=?str.replace(/FREE/g,?'<span?color="red">FREE</span>');

TA貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
這是一個(gè)使用切片和一些經(jīng)典串聯(lián)的工作示例。
編輯:現(xiàn)在還包括第二個(gè)字符串的代碼。
//get headline by id
var headline = document.getElementById("headline");
//declare your possible strings in vars
var string1 = "Get your FREE toothbrush!"
var string2 = "FREE floss set and dentures!"
//declare formatted span with "FREE" in var
var formattedFree = "<span style='color: blue; font-style: italic;'>FREE</span>"
//target positions for the rest of your string
var string1Position = 13
var string2Position = 4
//concat your vars into expected positions for each string
var 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 span
if (headline.innerHTML.includes(string1)) {
headline.innerHTML = newString1
}
else if (headline.innerHTML.includes(string2)) {
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>

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
您要查找的屬性是innerHTML,請(qǐng)查看以下示例:
var word = document.getElementById('word');
function changeWord(){
word.innerHTML = "another";
word.style.backgroundColor = 'black';
word.style.color = 'white';
}
<h1 id="headline">
<span id="word">some</span> base title
</h1>
<button onClick="changeWord()">
change
</button>

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以拆分文本并將關(guān)鍵字“FREE”轉(zhuǎn)換為 span 元素。因此您可以設(shè)置關(guān)鍵字“FREE”的樣式。此方法是安全的,因?yàn)椴粫?huì)更改任何非文本 html 元素。
var keyword = "FREE";
var headline = document.getElementById("headline");
var highlight, index;
headline.childNodes.forEach(child => {
if (child.nodeType == Node.TEXT_NODE) {
while ((index = child.textContent.indexOf(keyword)) != -1) {
highlight = child.splitText(index);
child = highlight.splitText(keyword.length);
with(headline.insertBefore(document.createElement("span"), highlight)) {
appendChild(highlight);
className = 'highlight';
}
}
}
});
.highlight {
/* style your keyword */
background-color: yellow;
}
<div id="FREE">
<h1 id="headline">"Get your FREE toothbrush! FREE floss set and dentures!"</h1>
</div>
添加回答
舉報(bào)