我在一个可疑的div
中有几个元素。如何将键盘插入符号放在由id标识的特定元素的末尾,然后使用Rangy将其移至div
的末尾?
提前致谢并感谢任何帮助。
答案 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);
一些重要说明: