获取并设置内容可编辑div中的光标位置

编程入门 行业动态 更新时间:2024-10-13 18:23:47
本文介绍了获取并设置内容可编辑div中的光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在内容可编辑的div中,我希望获取并设置光标位置,但不考虑子元素(例如 , 等).

in a content editable div, i wish get and set cursor position but but without taking into account the child elements (, , etc for example).

为了得到,我找到了这个解决方案:获取相对于其父容器的范围的开始和结束偏移量

for get, i find this solution : Get a range's start and end offset's relative to its parent container

但是我不知道.

请你能帮我吗?

谢谢你

推荐答案

您可以使用 rangy 自己定义它,就像这样:

You can use rangy to define it yourself, just like this:

var selector = document.querySelector('[contenteditable]'); var setCaretIndex = function (index) { var charIndex = 0, stop = {}; var traverseNodes = function (node) { if (node.nodeType === 3) { var nextCharIndex = charIndex + node.length; if (index >= charIndex && index <= nextCharIndex) { rangy.getSelection().collapse(node, index - charIndex); throw stop; } charIndex = nextCharIndex; } // Count an empty element as a single character. The list below may not be exhaustive. else if (node.nodeType === 1 && /^(input|br|img|col|area|link|meta|link|param|base)$/i.test(node.nodeName)) { charIndex += 1; } else { var child = node.firstChild; while (child) { traverseNodes(child); child = child.nextSibling; } } }; try { traverseNodes(selector); } catch (ex) { if (ex !== stop) throw ex; } };

要使用此功能,您需要先将编辑器聚焦:

To use this function, you need to focus the editor first:

selector.focus();

然后给出一个索引来设置光标位置:

Then giving an index to set cursor position:

setCaretIndex(3);

小提琴

更多推荐

获取并设置内容可编辑div中的光标位置

本文发布于:2023-10-08 01:18:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471087.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:光标   位置   编辑   容可   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!