首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何为某个div运行queryCommandState (而不是整个页面)?

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

Stack Overflow用户
提问于 2019-11-07 23:38:33
回答 1查看 226关注 0票数 0

如何检测一个项是否为粗体,仅在我的 div中,而不是当用户单击整个页面上的其他位置时?

这是我的JSFiddle和代码。

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

我搜索了一段时间却什么都找不到。我尝试以几种不同的方式将div选择器$(".text-editor")替换/添加到单词document中,这是行不通的。我觉得我漏掉了一些显而易见的东西。谢谢!

HTML:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
.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:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-08 00:16:20

您可以先检查contenteditable是否是焦点所在,然后再进行任何操作。

代码语言:javascript
复制
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事件上绑定。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58758418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档