Javascript 将插入符号移动到 contenteditable 中的搜索字符串

Javascript to move caret to a search string in a contenteditable

我有一个 contenteditable div,我需要将插入符号移动到字符串的某个位置,但我不知道该怎么做。有人有什么建议吗?

<div id='mydiv' contenteditable='true'>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Sed eget libero sit <mark>amet</mark> and **peekabo** magna sagittis sagittis quis nec risus.
    Pellentesque feugiat pharetra purus id pharetra.
</div>

<script>
doFindStringAndMoveCaret('mydiv', 'peekabo');


function doFindStringAndMoveCaret(elem, searchFor) { 
    // Find searchFor string in the elem.innerHTML, and then move the 
    // cursor to the beginning of that text

    ??
}

理想的普通老式 javascript(不是 jQuery)

谢谢 阿部

document.getElementById(elem).focus

试试这个 或者这个

textSelect(document.getElementById(elem), 1);

function doFindStringAndMoveCaret(elem, text) {
  function setCurrentCursorPosition(element, chars) {
    element.focus()
    if (chars >= 0) {
      var selection = window.getSelection();

      range = createRange(element.parentNode, {
        count: chars
      });

      if (range) {
        range.collapse(false);
        selection.removeAllRanges();
        selection.addRange(range);
      }
    }

    function createRange(node, chars, range) {
      if (!range) {
        range = document.createRange()
        range.selectNode(node);
        range.setStart(node, 0);
      }

      if (chars.count === 0) {
        range.setEnd(node, chars.count);
      } else if (node && chars.count > 0) {
        if (node.nodeType === Node.TEXT_NODE) {
          if (node.textContent.length < chars.count) {
            chars.count -= node.textContent.length;
          } else {
            range.setEnd(node, chars.count);
            chars.count = 0;
          }
        } else {
          for (var lp = 0; lp < node.childNodes.length; lp++) {
            range = createRange(node.childNodes[lp], chars, range);

            if (chars.count === 0) {
              break;
            }
          }
        }
      }

      return range;
    }
  }

  setCurrentCursorPosition(elem, new RegExp(text).exec(elem.innerHTML).index - 1)
}

doFindStringAndMoveCaret(document.getElementById('mydiv'), 'peekabo')
<div id='mydiv' contenteditable='true'>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  Sed eget libero sit <mark>amet</mark> and **peekabo** magna sagittis sagittis quis nec risus.
  Pellentesque feugiat pharetra purus id pharetra.
</div>

这只是找到字符串在divinnerHTML中的位置,从中减去1,并使用setCurrentCursorPosition聚焦div 并将光标移动到那里:

setCurrentCursorPosition(elem, new RegExp(text).exec(elem.innerHTML).index - 1)

函数中的其余代码修改并取自。

如果要将光标移动到文本的开始,请使用

setCurrentCursorPosition(elem, new RegExp(text).exec(elem.innerHTML).index - text.length - 1)

相反。

function doFindStringAndMoveCaret(elem, text) {
  function setCurrentCursorPosition(element, chars) {
    element.focus()
    if (chars >= 0) {
      var selection = window.getSelection();

      range = createRange(element.parentNode, {
        count: chars
      });

      if (range) {
        range.collapse(false);
        selection.removeAllRanges();
        selection.addRange(range);
      }
    }

    function createRange(node, chars, range) {
      if (!range) {
        range = document.createRange()
        range.selectNode(node);
        range.setStart(node, 0);
      }

      if (chars.count === 0) {
        range.setEnd(node, chars.count);
      } else if (node && chars.count > 0) {
        if (node.nodeType === Node.TEXT_NODE) {
          if (node.textContent.length < chars.count) {
            chars.count -= node.textContent.length;
          } else {
            range.setEnd(node, chars.count);
            chars.count = 0;
          }
        } else {
          for (var lp = 0; lp < node.childNodes.length; lp++) {
            range = createRange(node.childNodes[lp], chars, range);

            if (chars.count === 0) {
              break;
            }
          }
        }
      }

      return range;
    }
  }

  setCurrentCursorPosition(elem, new RegExp(text).exec(elem.innerHTML).index - text.length - 1)
}

doFindStringAndMoveCaret(document.getElementById('mydiv'), 'peekabo')
<div id='mydiv' contenteditable='true'>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  Sed eget libero sit <mark>amet</mark> and **peekabo** magna sagittis sagittis quis nec risus.
  Pellentesque feugiat pharetra purus id pharetra.
</div>

好的,我想我终于做到了。

function doFindStringAndMoveCaret(editor, findTx) {
        treeObject = {}
        var element = editor;
        editor.focus();

        function doTreeWalk(element, object) {
            var nodeList = element.childNodes;
            if (nodeList != null) {
                if (nodeList.length) {
                    object[element.nodeName] = []; 

                    for (var i = 0; i < nodeList.length; i++) {

                        if (nodeList[i].nodeType == 3) {
                            var p=nodeList[i].nodeValue.indexOf(findTx);
                            if ( p!=-1 ) {
                                var sel=window.getSelection();
                                var range=sel.getRangeAt(0);
                                range.setStart(nodeList[i], p);
                                range.setEnd(nodeList[i], p+findTx.length);
                                return;
                            }
                        }
                        else {
                            object[element.nodeName].push({});
                            doTreeWalk(nodeList[i]
                            , object[element.nodeName][object[element.nodeName].length - 1]);
                        }
                    }
                }
            }
        }

        doTreeWalk(element, treeObject);
        return;
    }
    doFindStringAndMoveCaret(document.getElementById('mydiv'), 'peekabo');

可以在 https://jsfiddle.net/Abeeee/krLeop49/6/

上找到工作示例

总之谢谢

问候 安倍