javascript - window.getSelection() 的值在回调期间发生变化

标签 javascript callback getselection

我试图存储 window.getSelection() 的值,但如果用户选择另一个选择,这个值似乎会改变。

在我下面的代码中,我存储了初始用户的选择。然后我创建我的表单(这需要一些时间),当表单创建完成后,我用用户的选择填写表单。现在在创建表单期间,用户可能会选择一些其他文本,现在存储在我的选择变量中的对象已经改变。我如何防止选择的值被更改?

var selection = window.getSelection();

createForm(function() {
    fillInForm(selection);
});

编辑 - 我需要保留选择的 DOM 结构,因为表单引用了所选文本的位置。

最佳答案

getSelection 函数返回 Selection目的。每个文档只能有一个选择对象,因此如果用户进行新选择,则与选择关联的范围必须更改。

The user agent should allow the user to change the active document's selection. If the user makes any modification to a selection, the user agent must create a new range with suitable start and end and associate the selection with this new range (not modify the existing range).

[...]

If the user changes the selection or a script calls addRange(), the selection must be associated with a new range object, as required elsewhere in this specification.

http://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#selections

关于javascript - window.getSelection() 的值在回调期间发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9649818/

相关文章:

javascript - 数组和 pureCompulated 值

c - 为什么要将指针转换为函数

javascript - 如何在 ipad 中用 div 包裹选定的文本?

javascript - Range startContainer 不是最深的节点

javascript - window.getSelection() 不给出 html 节点

对象结构的Javascript转换数组

javascript - 使用 React-Hooks,如何防止从 Array.map 创建的组件在其中一个兄弟组件更改状态时重新呈现?

javascript - 使用 WebSocket 连接到标准套接字

javascript - 试图理解回调函数的学生

java - Google Play 游戏成就 onClose 回调