javascript - 有没有办法确定 execCommand('bold') 现在是否正在执行?
问题描述
我正在构建一个带有粗体功能的简单 JavaScript 文本编辑器。我正在使用execCommand('bold')
这个。对于工具栏中的粗体图标,我必须检查我现在是否写粗体。我正在考虑每次执行命令时都会设置一个布尔变量,但这是不可能的,因为可以选择文本等等。
那么有没有办法确定 execCommand('bold') 现在是否正在执行?
解决方案
您需要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>
推荐阅读
- python - 递归函数查找到特定目标的所有路径
- c++ - 返回文件开头后,循环中的 ifstream 停留在相同的值上
- javascript - 使用 React 获取箭头函数的返回值
- java - 如何在没有 layout.xml 的情况下以编程方式创建 AdView
- html - 如何在浏览器放大/缩小期间保持 SVG 大小相同
- angular - 将 ng-template 从一个组件传递到另一个组件内部的 ng-select
- x86 - 如何在英特尔环网架构上选择引导处理器 (BSP)
- c# - Unity - 为什么带有图像的材料会出现故障?仅在构建中?
- google-cloud-platform - 如何避免在谷歌云实例上安装相同的软件?
- python - 无法填充表格小部件的某些单元格。PyQt5