使用Rangy将键盘插入符移动到元素的末尾

时间:2013-08-21 07:12:31

标签: javascript html html5 rangy

我在一个可疑的div中有几个元素。如何将键盘插入符号放在由id标识的特定元素的末尾,然后使用Rangy将其移至div的末尾?

提前致谢并感谢任何帮助。

1 个答案:

答案 0 :(得分:7)

要在特定元素后设置插入符号,您需要创建一个范围并将该范围应用于浏览器的选择对象,如下所示:

//get the browser selection object - it may or may not have a selected range
var selectionn = rangy.getSelection();

//create a range object to set the caret positioning for
var range = rangy.createRange();

//get the node of the element you wish to put the caret after
var startNode = document.getElementById('YourTagID');

//set the caret after the node for this range
range.setStartAfter(startNode);
range.setEndAfter(startNode);

//apply this range to the selection object
selection.removeAllRanges();
selection.addRange(range);

在某些时候,如果您想移动插入符号,那么您可以执行与上面相同的操作,在“DIV”之后移动它,但是如果您希望选择范围从“A”标记后移动到在你的'DIV'标签之后,你会这样做:

//get the browser selection object - it may or may not have a selected range
var selectionn = rangy.getSelection();

//create a range object to set the caret positioning for
var range = rangy.createRange();

//get the nodes of the elements you wish to put the range between
var startNode = document.getElementById('YourTagID');
var endNode = document.getElementById('YourDivTagID');

//set the caret after the node for this range
range.setStartAfter(startNode);
range.setEndAfter(endNode);

//apply this range to the selection object
selection.removeAllRanges();
selection.addRange(range);

如果您希望您的选择位于元素的末尾,但是在元素内部而不是在元素之后,那么您将执行类似的操作。

//get the browser selection object - it may or may not have a selected range
var selectionn = rangy.getSelection();

//create a range object to set the caret positioning for
var range = rangy.createRange();

//get the nodes of the elements you wish to put the range between
var startNode = document.getElementById('YourTagID');
var endNode = document.getElementById('YourDivTagID');

//set the caret after the start node and at the end of the end node
//Note: the end is set using endNode.length when the node is of the text type
//and it is set using childNodes.length when the end node is of the element type
range.setStartAfter(startNode);
range.setEnd(endNode, endNode.length || endNode.childNodes.length);

//apply this range to the selection object
selection.removeAllRanges();
selection.addRange(range);

一些重要说明:

  1. 您不必按ID获取开始或结束节点,但您必须以某种方式从DOM获取Node对象。
  2. 如果您修改DOM,那么您可能正在销毁过程中的范围对象。这就是为什么第二个代码块完成了重新创建范围的工作,而不仅仅是引用现有范围。