如何以编程方式突出显示可内容编辑的 div 中的文本

问题描述 投票:0回答:1

我正在尝试找到一种方法来以编程方式选择可内容编辑的 div 中的特定文本,但没有任何运气。 对于文本区域和输入字段,我可以按如下方式轻松完成此操作;

      const el = document.getElementById("some_input_field");
      const words = "Find me";
      searchText = el.value;  //Would use el.textContent for contenteditable div, not innerHTML
      if (searchText !== "") {
        foundPosition = findText(searchText, words); //Returns the start and end index of the first match ie: [5,14]
        if (foundPosition != []) {
          el.focus();
          el.setSelectionRange(foundPosition[0], foundPosition[1]); //This is where i want to highlight the text
        } else {
          console.log("Word(s) not found in text");
        }
      } else {
        console.log("No text to search");
      }

但我无法弄清楚如何在 contenteditable div 中执行此操作。有很多根据索引选择整个内容而不是特定文本的例子。我知道如何在 div 中突出显示文本,但我只是不知道如何以编程方式突出显示它。 我花了很多时间只是突出显示 div 中的一段文本并查看属性,看看是否可以使用它来解决这个问题,但我遇到了死胡同。 我无法想象没有办法做到这一点。我希望有人已经做到了这一点并可以提供一些帮助。 谢谢,

javascript contenteditable
1个回答
0
投票

你可以这样做(这个例子有点过头了)。

const div = document.querySelector("div");
const btn = document.querySelector("button");
const inp = document.querySelector("#txt");
const chkCase = document.querySelector("#chkCase");

btn.addEventListener("click",function() {
  let txt = inp.value;
  if(txt) {
    find(txt,div);
  }
});

function find(needle, haystack) {
  let sel = window.getSelection();
  let range = document.createRange();
  let state = chkCase.checked;
  let hayTxt = haystack.textContent;

  if(!state) {
    hayTxt = hayTxt.toLowerCase();
    needle = needle.toLowerCase();
  }

  if(hayTxt.indexOf(needle) >= 0) {
    range.setStart(haystack.childNodes[0], hayTxt.indexOf(needle));
    range.setEnd(haystack.childNodes[0], hayTxt.indexOf(needle) + needle.length);

    sel.removeAllRanges();
    sel.addRange(range);
  }
}
<div contenteditable="true">Where's Waldo? Where in the world is Carmen Sandiego? They both say "Find me". Well, maybe not Carmen.</div>
<button type="button">Find</button>
<input type="text" name="txt" id="txt" value="Find me">
<input type="checkbox" name="chkCase" id="chkCase" value="1" checked>Case sensitive?

我知道这不在您的原始代码中,但我想给您一个示例,该示例可以与您在

contenteditable
元素中输入的任何内容一起使用 - 这就是输入和按钮的用途。

© www.soinside.com 2019 - 2024. All rights reserved.