首页 > 解决方案 > 在 contentediatable div 中的子字符串末尾设置光标

问题描述

在这里,用户输入一些字符串,字符串包含Mahi作为子字符串。我试图将光标Mahi放在单击按钮的末尾?

.html

<div id="demo" contenteditable="true"></div>

<button id="btn" onclick="focusAtMen()"></button>

js

// lets suppose user input is "Hi.......Mahi, .....?";
// here dots may be any characters

focusAtMen(){
var editor = document.getElementById("demo");
// set focus on `contentEditable div` and `place cursor at the end` of `Mahi` , thats a user Input.

}

标签: javascriptjquery

解决方案


您可以使用Range.setStartSelection来获取光标插入符号的位置。setStart 函数将一个节点和一个偏移量作为该节点内的起始位置。

下面的代码处理Mari文本中出现的情况。它还处理Mari不包含在字符串中的情况,在这种情况下,它将插入符号放在文本的最后一个字符处。

function focusAtMen() {
  var textToFind = 'Mahi';
  var editor = document.getElementById("demo");

  var range = document.createRange();
  var sel = window.getSelection();
  
  // get the index of the start of 'Mahi'
  var indexOfMahi = editor.innerText.lastIndexOf(textToFind);
  
  if (indexOfMahi > -1) {
      // if text contains Mari
      range.setStart(editor.childNodes[0], indexOfMahi + textToFind.length);
  } else if (editor.innerText.length > 0) {     
     // if text does not contain Mari set cursor to the end of the string 
     range.setStart(editor.childNodes[0], editor.innerText.length);
  } else {
     // there is no text
     range.setStart(editor, 0);
  }
  
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
}
<div id="demo" contenteditable="true">some text Mahi and another Mahi included</div>
<button id="btn" onclick="focusAtMen()">Click</button>

请注意,上面的代码区分大小写,如果您需要此代码,则mari需要Mari对其进行相应修改。


推荐阅读