【问题标题】:How do I run queryCommandState for a certain div (and not the whole page)?如何为某个 div(而不是整个页面)运行 queryCommandState?
【发布时间】:2019-11-07 23:38:33
【问题描述】:

如何仅在我的 contenteditable div 内检测项目是否为 bold,而不是在用户单击整个页面上的其他任何位置时检测?

Here's my JSFiddle with the code.

我正在尝试运行 document.queryCommandState("bold") 但仅适用于我的 contenteditable="true" div。

我用谷歌搜索了一段时间,找不到任何东西。我尝试以几种不同的方式将我的 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)

【问题讨论】:

    标签: javascript jquery wysiwyg contenteditable rich-text-editor


    【解决方案1】:

    您可以先检查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 事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      相关资源
      最近更新 更多