如何用JavaScript实现正在输入中文本的粗体功能?
实现类似Word/Google Docs的选中文本粗体功能
当然可以实现,核心是针对用户选中的文本进行样式切换,而不是给整个文本容器统一加样式。下面给你两种可行的实现方式:
方法一:用document.execCommand快速实现(兼容性好)
这个API虽然被部分浏览器标记为过时,但目前绝大多数浏览器都还支持,而且代码极简,完全能满足需求:
boldBtn.onclick = () => { // 调用bold命令,自动切换选中文本的粗体状态 document.execCommand('bold', false, null); }
- 选中文本后点击按钮,会给选中内容包裹
<strong>标签实现粗体; - 没选中文本时点击,后续输入的文本会自动变成粗体,再次点击恢复正常;
- 重复点击可以切换粗体/正常状态,和Word、Google Docs的逻辑完全一致。
方法二:用Selection+Range API手动实现(更现代可控)
如果不想用标记为过时的API,可以用原生的选区和范围API手动操作DOM,适合需要自定义逻辑的场景。假设你的编辑区域是一个contenteditable的容器:
<div id="editor" contenteditable="true" style="min-height: 100px; border: 1px solid #ccc;"></div> <button id="boldBtn">粗体</button>
对应的JavaScript代码:
const boldBtn = document.getElementById('boldBtn'); const editor = document.getElementById('editor'); boldBtn.onclick = () => { const selection = window.getSelection(); // 没有选区的话直接返回 if (selection.rangeCount === 0) return; const range = selection.getRangeAt(0); // 判断当前选区是否已经是粗体状态 const isCurrentlyBold = document.queryCommandState('bold'); if (isCurrentlyBold) { // 取消粗体:移除选中区域内的<strong>标签,保留文本内容 const boldNodes = Array.from(range.commonAncestorContainer.querySelectorAll('strong')); boldNodes.forEach(node => { const parent = node.parentNode; parent.replaceChild(document.createTextNode(node.textContent), node); // 合并相邻文本节点,避免DOM冗余 parent.normalize(); }); } else { // 添加粗体:把选中内容包裹在<strong>标签里 const boldElement = document.createElement('strong'); range.surroundContents(boldElement); } // 恢复选区,避免操作后选中状态丢失 selection.removeAllRanges(); selection.addRange(range); };
- 这种方式可以完全控制DOM结构,适合需要和其他富文本功能(比如斜体、下划线)配合的复杂场景;
- 注意要给编辑区域设置
contenteditable="true",让它支持文本输入和选中。
内容的提问来源于stack exchange,提问作者Kuzi
相关产品推荐
相关产品推荐

