javascript - 在 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.
}
解决方案
您可以使用Range.setStart和Selection来获取光标插入符号的位置。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
对其进行相应修改。
推荐阅读
- spring-boot - Maven 为 SpringBoot REST 控制器生成 OpenAPI JSON
- windows - 我是否需要分别为每个 opengl 上下文加载函数?
- r - 如何启动 RStudio 以指向 Windows 上的非默认 R 版本
- angular - 调用验证函数后使表单有效的问题
- node.js - 我一直收到此架构未注册的错误。有没有办法解决这个错误?
- azure - 如何在 Azure Function App 中恢复已删除的 WEBSITE_CONTENTSHARE 配置值
- typescript - 一般键入一个接受两个相同类型参数的函数
- c# - 根据 ASP.NET MVC 中的条件选择特定枚举到 EnumDropDownListFor
- python - 通过列中的常见字符串合并多个熊猫数据框
- python - SettingWithCopyWarning 是什么意思?