簡體   English   中英

如何為某個 div(而不是整個頁面)運行 queryCommandState?

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

如何檢測項目是否為粗體,僅在我的contenteditable div 中,而不是當用戶單擊整個頁面上的其他任何位置時?

這是我的 JSFiddle 代碼。

我正在嘗試運行document.queryCommandState("bold")但僅適用於我的contenteditable="true" div。

我用谷歌搜索了一段時間,找不到任何東西。 我嘗試以幾種不同的方式將我的 div 選擇器$(".text-editor")替換/添加到 word文檔中,但這是行不通的。 我覺得我錯過了一些明顯的東西。 謝謝!


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事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM