简体   繁体   English

如何为某个 div(而不是整个页面)运行 queryCommandState?

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

How do I detect if an item is bold , ONLY within my contenteditable div, and not when the user clicks anywhere else on the entire page?如何检测项目是否为粗体,仅在我的contenteditable div 中,而不是当用户单击整个页面上的其他任何位置时?

Here's my JSFiddle with the code.这是我的 JSFiddle 代码。

I'm trying to run document.queryCommandState("bold") but only for my contenteditable="true" div.我正在尝试运行document.queryCommandState("bold")但仅适用于我的contenteditable="true" div。

I've googled for a while and can't find anything.我用谷歌搜索了一段时间,找不到任何东西。 I've tried replacing/adding my div selector $(".text-editor") to the word document in a few different ways, which doesn't work.我尝试以几种不同的方式将我的 div 选择器$(".text-editor")替换/添加到 word文档中,但这是行不通的。 I feel like I'm missing something obvious.我觉得我错过了一些明显的东西。 Thanks!谢谢!


HTML: 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: 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: 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)

You can check if contenteditable is being focused first, before doing any of that.在执行任何操作之前,您可以检查是否首先关注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)

Also setInterval is not necessary here.这里也不需要setInterval You can bind on click event for example.例如,您可以绑定click事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM