这是您的解决方案。
function changeBold() {
const text = window.getSelection().toString();
var span = document.createElement('span');
span.innerHTML = text;
span.style.fontWeight = 'bold';
document.execCommand('insertHTML', false, span.outerHTML);
}
<p contenteditable="true" id="contenttxt">
Some text in this paragraph tag
</p>
<button onclick="changeBold()">Bold selected text</button>
可以使用span标签并添加ID
function changeBold() {
document.getElementById("strongC").style.fontWeight = "600";
}
<p contenteditable="true" id="contenttxt">
<span id="strongC">Some text</span>
in this paragraph tag
</p>
<button onclick="changeBold()">Bold selected text</button>