如何检测一个项是否为粗体,仅在我的 div中,而不是当用户单击整个页面上的其他位置时?
这是我的JSFiddle和代码。
我正在尝试运行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)发布于 2019-11-08 00:16:20
您可以先检查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事件上绑定。
https://stackoverflow.com/questions/58758418
复制相似问题