本文介绍了获取并设置内容可编辑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中的光标位置
发布评论