1 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
這樣做的一種方法可能是執(zhí)行以下操作:
獲取窗口選擇。
將選擇轉(zhuǎn)換為字符串以獲取文本。
創(chuàng)建將是粗體的元素。
更換包含在所選文本
innerHTML
的parentElement
用粗體顯示的元素。
基于您提供的代碼的示例:
let boldBtn = document.getElementById('Bold-Btn');
let boldClickListener = (event) => {
event.preventDefault();
// Get selection
let selection = window.getSelection();
// Get string of text from selection
let text = selection.toString();
// Create bolded element that will replace the selected text
let final = `<span class="text-bold">${text}</span>`;
// Replace the selected text with the bolded element
selection.anchorNode.parentElement.innerHTML = selection.anchorNode.parentElement.innerHTML.replace(text, final);
};
boldBtn.addEventListener('click', boldClickListener);
.text-bold {
font-weight: bold;
}
<div>
Test this text
</div>
<button id="Bold-Btn">
Bold
</button>
請(qǐng)注意,您可能希望在創(chuàng)建粗體元素時(shí)添加更多邏輯來處理任何現(xiàn)有文本是否已經(jīng)是粗體。
添加回答
舉報(bào)