Document: phương thức queryCommandState()
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
Non-standard: This feature is not standardized. We do not recommend using non-standard features in production, as they have limited browser support, and may change or be removed. However, they can be a suitable alternative in specific cases where no standard option exists.
Note:
Mặc dù phương thức execCommand() đã lỗi thời, vẫn có một số trường hợp sử dụng hợp lệ chưa có giải pháp thay thế khả thi, như đã đề cập trong bài viết về execCommand(). Trong những trường hợp này, bạn có thể thấy phương thức này hữu ích để triển khai trải nghiệm người dùng hoàn chỉnh, nhưng hãy kiểm tra để đảm bảo tương thích trình duyệt.
Phương thức queryCommandState() sẽ cho bạn biết nếu vùng chọn hiện tại có một lệnh Document.execCommand() cụ thể được áp dụng.
Cú pháp
queryCommandState(command)
Tham số
command-
Một lệnh từ
Document.execCommand()
Giá trị trả về
queryCommandState() có thể trả về một giá trị boolean hoặc null nếu trạng thái không xác định.
Ví dụ
>HTML
<div contenteditable="true">Select a part of this text!</div>
<button>Kiểm tra trạng thái của lệnh 'bold'</button>
<hr />
<div id="output"></div>
JavaScript
function makeBold() {
const state = document.queryCommandState("bold");
let message;
switch (state) {
case true:
message = "Định dạng in đậm sẽ bị xóa khỏi văn bản đã chọn.";
break;
case false:
message = "Văn bản đã chọn sẽ được hiển thị in đậm.";
break;
default:
message = "Trạng thái của lệnh 'bold' không thể xác định.";
break;
}
document.querySelector("#output").textContent = `Output: ${message}`;
document.execCommand("bold");
}
document.querySelector("button").addEventListener("click", makeBold);
Kết quả
Đặc tả kỹ thuật
Tính năng này không thuộc bất kỳ đặc tả kỹ thuật hiện tại nào. Nó không còn nằm trong lộ trình trở thành tiêu chuẩn. Có một bản nháp đặc tả W3C execCommand không chính thức.
Tương thích trình duyệt
Xem thêm
HTMLElement.contentEditabledocument.designModedocument.execCommand()- Các lỗi trình duyệt liên quan đến
queryCommandState(): Tài liệu "Browser Inconsistencies" của Scribe