我如何 运行 查询某个 div(而不是整个页面)的 queryCommandState?

How do I run queryCommandState for a certain div (and not the whole page)?

我如何检测一个项目是否 bold,仅在我的 contenteditable div 中,而不是当用户点击整个页面上的其他任何地方?

Here's my JSFiddle with the code.

我正在尝试 运行 document.queryCommandState("bold") 但仅针对我的 contenteditable="true"div.

我用谷歌搜索了一段时间,但找不到任何东西。我已经尝试 replacing/adding 我的 div 选择器 $(".text-editor")document 中的单词几种不同的方式,这是行不通的。我觉得我错过了一些明显的东西。谢谢!


HTML:

<div contenteditable="true" class="text-editor">Content <b>editable</b>. Type here...</div>

<div class="normal-div">Content <b>not</b> editable.</div>

Click on the bold (and not bold) text in the two boxes. Result:
<div class="is-bold">The text your cursor's on is BOLD.</div>

<div class="is-not-bold">The text your cursor's on is NOT BOLD.</div>

<br>^^ I want this green result to only change when you're clicking inside the editable box.

CSS:

.text-editor {
  border: 2px solid red;
  margin-bottom: 10px;
}

.normal-div {
  border: 2px solid blue;
  margin-bottom: 10px;
}

.is-bold {
  display: none;
  color: green;
}

.is-not-bold {
  display: none;
  color: green;
}

.active {
  display: block;
}

jQuery:

setInterval(function () {
    var isItBold = document.queryCommandState("bold");
    if (isItBold == true) { 
    $(".is-bold").addClass("active");
    $(".is-not-bold").removeClass("active"); 
  }
  else { 
    $(".is-bold").removeClass("active");
    $(".is-not-bold").addClass("active"); 
  }
}, 100)

您可以先检查 contenteditable 是否正在集中注意力,然后再进行任何操作。

var editable = $("[contenteditable]")

setInterval(function () {
    if (!editable.is(":focus")) return

    var isItBold = document.queryCommandState("bold");
    if (isItBold == true) { 
    $(".is-bold").addClass("active");
    $(".is-not-bold").removeClass("active"); 
  }
  else { 
    $(".is-bold").removeClass("active");
    $(".is-not-bold").addClass("active"); 
  }
}, 100)

这里也不需要setInterval。例如,您可以绑定 click 事件。