簡體   English   中英

Javascript - 如何在文本字符串中設置特定單詞的樣式?

[英]Javascript - How to style specific word in a string of text?

我在這里有一串文本,它將被動態生成為以下內容之一:

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

OR

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

由於這將是動態生成的,因此我無法將<span>包裹在“FREE”一詞周圍,因此我想使用 Javascript 專門針對“FREE”一詞,以便我可以使用不同的字體系列對其進行樣式設置和font-color 比<h1>設置的任何樣式。 我用什么方法來做這件事?

您可以使用樣式化的 HTML 搜索和替換子字符串“FREE”。 如果“FREE”在字符串中出現多次,您可能需要使用正則表達式(除非您不需要支持 Internet Explorer)。 請參閱如何替換所有出現的字符串?

在你的情況下:

let str = '<h1 id="headline">"FREE floss set and dentures!"</h1>'
str = str.replace(/FREE/g, '<span color="red">FREE</span>');

你要找的屬性是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>

這是一個使用切片和一些經典連接的工作示例。

編輯:現在還包括第二個字符串的代碼。

 //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>

您可以拆分文本並將關鍵字“FREE”轉換為跨度元素。 因此,您可以設置關鍵字“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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM