gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:12:31 26 4
gpt4 key购买 nike

我在一个 contenteditable div 中有几个 a 元素。如何将键盘插入符放在由 id 标识的特定元素的末尾,然后使用 Rangy 将其移动到 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 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 中获取节点对象本身。
  2. 如果您修改 DOM,那么您可能会在此过程中破坏您的范围对象。这就是为什么第二个代码块会重新创建范围,而不是仅仅引用现有范围。

关于javascript - 使用 Rangy 将键盘插入符号移动到元素的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18351001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com