首页 > 解决方案 > 有没有办法确定 execCommand('bold') 现在是否正在执行?

问题描述

我正在构建一个带有粗体功能的简单 JavaScript 文本编辑器。我正在使用execCommand('bold')这个。对于工具栏中的粗体图标,我必须检查我现在是否写粗体。我正在考虑每次执行命令时都会设置一个布尔变量,但这是不可能的,因为可以选择文本等等。

那么有没有办法确定 execCommand('bold') 现在是否正在执行?

标签: javascripthtml

解决方案


您需要Document.queryCommandState()方法。

bolder.onclick = e => {
  document.execCommand('bold');
};

inp.onfocus = document.onselectionchange = e =>
  bolder.classList.toggle('active', isWritingBold());

function isWritingBold() {
  return document.queryCommandState('bold');
}
#bolder.active::before {
  content: 'un-';
}
<button id="bolder">boldify current selection</button>
<div id="inp" contenteditable>edit me and <b>boldify</b> any part of my content</div>


推荐阅读