4 回答

TA貢獻1862條經驗 獲得超6個贊
您可以搜索子字符串“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>');

TA貢獻1893條經驗 獲得超10個贊
這是一個使用切片和一些經典串聯的工作示例。
編輯:現在還包括第二個字符串的代碼。
//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貢獻1817條經驗 獲得超14個贊
您要查找的屬性是innerHTML,請查看以下示例:
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貢獻1801條經驗 獲得超8個贊
您可以拆分文本并將關鍵字“FREE”轉換為 span 元素。因此您可以設置關鍵字“FREE”的樣式。此方法是安全的,因為不會更改任何非文本 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>
添加回答
舉報