文件: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 規範草案

瀏覽器相容性

另見