我该如何修改它如何在contenteditable元素(div)中设置caret(cursor)位置?使其接受数字索引和元素,并将光标位置设置为该索引?
例如:如果我有以下段落:
<p contenteditable="true">This is a paragraph.</p>
我打电话给:
setCaret($(this).get(0), 3)
光标将移动到索引3,如下所示:
Thi|s is a paragraph.
我有这个,但是没有运气:
function setCaret(contentEditableElement, index) { var range,selection; if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+ { range = document.createRange();//Create a range (a range is a like the selection but invisible) range.setStart(contentEditableElement,index); range.collapse(true); selection = window.getSelection();//get the selection object (allows you to change selection) selection.removeAllRanges();//remove any selections already made selection.addRange(range);//make the range you have just created the visible selection } else if(document.selection)//IE 8 and lower { range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible) range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start range.select();//Select the range (make it the visible selection } }
这是从HTML中选择后持久保留范围对象的更改而来的一个答案。请记住,这在几个方面都不是完美的(就像使用相同方法的MaxArt一样):首先,仅考虑文本节点,这意味着<br>索引所隐含的换行符和块元素不包括在索引中;其次,考虑所有文本节点,甚至是那些被CSS隐藏的内部<script>元素或内部元素。第三,连续折叠在页面上的空白字符都包含在索引中;最后,IE<= 8的规则再次有所不同,因为它使用了不同的机制。
<br>
<script>
var setSelectionByCharacterOffsets = null; if (window.getSelection && document.createRange) { setSelectionByCharacterOffsets = function(containerEl, start, end) { var charIndex = 0, range = document.createRange(); range.setStart(containerEl, 0); range.collapse(true); var nodeStack = [containerEl], node, foundStart = false, stop = false; while (!stop && (node = nodeStack.pop())) { if (node.nodeType == 3) { var nextCharIndex = charIndex + node.length; if (!foundStart && start >= charIndex && start <= nextCharIndex) { range.setStart(node, start - charIndex); foundStart = true; } if (foundStart && end >= charIndex && end <= nextCharIndex) { range.setEnd(node, end - charIndex); stop = true; } charIndex = nextCharIndex; } else { var i = node.childNodes.length; while (i--) { nodeStack.push(node.childNodes[i]); } } } var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } } else if (document.selection) { setSelectionByCharacterOffsets = function(containerEl, start, end) { var textRange = document.body.createTextRange(); textRange.moveToElementText(containerEl); textRange.collapse(true); textRange.moveEnd("character", end); textRange.moveStart("character", start); textRange.select(); }; }