仅将样式应用于可编辑内容中的选定文本<p>

问题描述 投票:0回答:2
javascript html jquery css contenteditable
2个回答
4
投票

这是您的解决方案。

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>


1
投票

可以使用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>

© www.soinside.com 2019 - 2024. All rights reserved.