【发布时间】:2022-02-14 00:58:06
【问题描述】:
我正在尝试将文本更改为粗体,这真的很难。 我用各种方法尝试了很多次, 例如:
//1:
document.getElementById('boldtext').innerHTML = "<b>" += document.getElementById('boldtext').innerHTML += "</b>"; //which dosent work
//2:
document.getElementById('boldtext').bold(); //dosent work too
关于如何在 Javascript 中加粗文本有什么想法吗?
//My code so far:
The whole code is this: function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } alert(text); }; let BoldButton = document.createElement('input'); /*boldbuttonlol*/ BoldButton.type = 'button'; BoldButton.value = 'bold highlighted text'; BoldButton.onclick = () => { getSelectionText(); }; document.body.appendChild(BoldButton);
谢谢!!
【问题讨论】:
-
请使用“编辑”链接而不是 cmets 来改进/添加问题
-
无需在其周围添加
b标签,只需更改元素的样式:document.getElementById('boldtext').classList.add("bold")(假设您的CSS 中有一个名为bold的类,例如.bold { font-weight: bold; }或类似的) .或document.getElementById('boldtext').style.fontWeight = "bold";,但像这样更改内联样式通常不是最佳做法。 -
感谢您的帮助!!
标签: javascript html innerhtml