我的目標是用 span 元素替換檔案 P 標簽中的每個單詞。雖然下面的代碼在第一種情況下做得很好,但下面的代碼重疊,并開始完全破壞我們 P 標簽的 HTML 結構。請參閱影像以獲取不需要的輸出
想知道我的方法是錯誤的,還是需要一些魔法才能只影響標簽之間的 innerHTML?
const runBionic = (node: ChildNode, paragraph: HTMLElement):HTMLElement => {
if (node.textContent === null) return paragraph;
const originalWords:string[] = node.textContent.split(" ");
const filteredWords: string[] = originalWords.filter(word => word!=="" && word !== "\n");
console.log("Filtered words: ", filteredWords);
//replace each word with a span element
filteredWords.forEach(word => {
const modifiedWord = `<span style='font-weight: bold;'>${word}</span>`;
console.log("REPLACING ", word, "WITH ", modifiedWord);
paragraph.innerHTML = paragraph.innerHTML.replaceAll(word,modifiedWord);
});
return paragraph;};
旨在最終構建一個 chrome 擴展,突出顯示任何頁面上任何單詞的前 1/2 字符。這將幫助有閱讀障礙的人更快地閱讀網路。在 github 上附加指向整個 repo 的鏈接以獲取背景關系。
uj5u.com熱心網友回復:
好的,所以我最終用一個新的 span 元素替換了整個 TextNode。這樣我可以準備整個元素并將其附加到其父元素。完美運行,不需要正則運算式....
const replaceNode = (node: ChildNode)=>{
if (node.textContent === null) return node;
const newChild = document.createElement("span");
const words: string[] = node.textContent.split(" ").filter(word => word!=="" && word !== "\n");
const HTMLstring: string = spannify(words);
newChild.innerHTML = HTMLstring;
return newChild;};
const spannify = (words : string[]) : string=>{
let HTMLstring = "";
words.forEach(word =>{
const span = `<span> ${word} </span>`;
HTMLstring = span;
});
return HTMLstring;};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/493192.html
標籤:javascript 打字稿 dom 内部html
