文档:queryCommandState() 方法
已弃用:此特性不再推荐。虽然某些浏览器可能仍然支持它,但它可能已经从相关的网络标准中删除,可能正在删除过程中,或者可能仅为兼容性目的而保留。请避免使用它,如果可能,请更新现有代码;请参阅本页底部的兼容性表格以指导您的决策。请注意,此特性可能随时停止工作。
非标准:此特性未标准化。我们不建议在生产环境中使用非标准特性,因为它们浏览器支持有限,并且可能会更改或被移除。但是,在没有标准选项的特定情况下,它们可以是合适的替代方案。
注意:尽管 execCommand() 方法已被弃用,但仍有一些有效的使用场景尚无可行替代方案,正如 execCommand() 文章中所述。在这些情况下,您可能会发现此方法有助于实现完整的用户体验,但请进行测试以确保跨浏览器兼容性。
queryCommandState() 方法会告诉您当前选定的内容是否已应用了特定的 Document.execCommand() 命令。
语法
js
queryCommandState(command)
参数
command-
来自
Document.execCommand()的命令
返回值
queryCommandState() 可以返回一个布尔值,或者在状态未知时返回 null。
示例
HTML
html
<div contenteditable="true">Select a part of this text!</div>
<button>Test the state of the 'bold' command</button>
<hr />
<div id="output"></div>
JavaScript
js
function makeBold() {
const state = document.queryCommandState("bold");
let message;
switch (state) {
case true:
message = "The bold formatting will be removed from the selected text.";
break;
case false:
message = "The selected text will be displayed in bold.";
break;
default:
message = "The state of the 'bold' command is indeterminable.";
break;
}
document.querySelector("#output").textContent = `Output: ${message}`;
document.execCommand("bold");
}
document.querySelector("button").addEventListener("click", makeBold);
结果
规范
此功能不属于任何当前规范。它不再有望成为标准。有一个非官方的 W3C execCommand 规范草案。
浏览器兼容性
加载中…
另见
HTMLElement.contentEditabledocument.designModedocument.execCommand()- 与
queryCommandState()相关的浏览器错误:Scribe 的“浏览器不一致性”文档