簡體   English   中英

根據第一個字母將所有單個單詞包裝在一個 span 標簽中

[英]Wrap all individual words in a span tag based on their first letter

我試圖將網頁上的每個單詞包裝在一個標簽中,這樣我就可以根據它們的首字母分別設置它們的樣式。

我發現了這種將每個單詞單獨包裝在 span 標簽中的方法,但我不知道如何根據單詞的第一個字母來改變 class。

let e = document.getElementById('words');

e.innerHTML = e.innerHTML.replace(/(^|<\/?[^>]+>|\s+)([^\s<]+)/g, '$1<span class="word">$2</span>');

如果您想引用單個單詞,則無法使用正則表達式來完成您想要實現的目標。

我寫了一個使用document.querySelector()的小片段

查詢選擇器上的 outerText 屬性 object 返回純文本字符串,稍后使用split()將其轉換為數組 function

然后它簡單地遍歷數組並附加樣式標簽並獲取我使用的第一個字母substring() function

 const words = document.querySelector("#words").outerText.split(" "); const wordsDiv = document.querySelector("#words") wordsDiv.innerHTML = "" words.map((el) => { wordsDiv.innerHTML += `<span class="${el.substring(0, 1)}">${el}</span> ` })
 <div id="words">red green blue orange</div>

嘗試這個:

let e = document.getElementById('words');
// Create array with words
let words = e.innerHTML.split(' ');
// Object with CSS classes and corresponding letter
const classes = {
    a: 'class-one',
    b: 'class-two',
    // and so on
}
// Return array with the new strings
words = words.map(word => {
    const firstLetter = word.substring(0,1);
    return `<span class="${classes[firstLetter]}">${word}</span>`;
});
// Join the array and update the DOM
e.innerHTML = words.join(' ');

這里發生了以下情況:

  • 單詞被空格分隔,創建一個數組;
  • classes常量必須像示例中那樣接收每個字母與其 class 的對應關系;
  • map方法的 function 中,返回單詞的第一個字母,並使用該字母訪問類 object;
  • 最后,我們進行join以連接所有用空格分隔的文本。

請記住,如果單詞之間有多個空格,則會出現不一致,因為第一個字母將是一個空格。

string.prototype.replace引用中,您還可以將替換 function添加到方法中,而不是字符串。 替換 function 具有這種形式

所以,如果我沒有誤解你的問題,你可以做類似的事情:

let e = document.getElementById('words');

e.innerHTML = e.innerHTML.replace(/(^|<\/?[^>]+>|\s+)([^\s<]+)/g, function(match, p1, p2) {
    const myClasses = {
        a: "aword",
        b: "bword",
        ...
    }
    return `${p1}<span class="${myClasses[p2[0]]}">${p2}</span>'
});

你可以這樣做:

  1. Select 全體小朋友
  2. map 他們及其文本內容
  3. 將文本拆分為單個單詞
  4. map 再次使用一些樣式 html
  5. 加入、渲染和享受。

 words.innerHTML = [...words.children].flatMap(el => el.innerText.replace(/\n/ig, " ").split(" ")).map(el => `<div class="someClass">${el}</div>`).join("")
 .someClass { color: red; background: orange; margin: 10px; }
 <div id="words"> <div> Some dummy content <span>Some other nested dummy content</span> </div> <p>Some sibling content</p> </div>

暫無
暫無

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

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