阻止JavaScript window.getSelection()循环引用 [英] Prevent JavaScript window.getSelection() circular reference

查看:112
本文介绍了阻止JavaScript window.getSelection()循环引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅此演示(取决于此时仅在Chrome中有效的selectionchange事件): http://jsfiddle.net / fyG3H /

See this demo (dependent on selectionchange event which works in Chrome only at this moment): http://jsfiddle.net/fyG3H/

选择一些lorem ipsum文本然后聚焦文本输入。在控制台日志中,您将看到有一个DOMSelection对象。
它的anchorNode值为 HTMLBodyElement ,而它应该有一个 Text

Select some lorem ipsum text and then focus the text input. In the console log you will see that there is a DOMSelection object. It has an anchorNode value of HTMLBodyElement while it should have one of Text.

在我尝试对选择对象进行字符串处理之前,我不知道为什么会发生这种情况: http://jsfiddle.net/fyG3H/1/

I didn't know why this was happening until I tried stringfying the selection object: http://jsfiddle.net/fyG3H/1/

这会出现以下错误:


Uncaught TypeError:将循环结构转换为JSON

Uncaught TypeError: Converting circular structure to JSON

你知道我怎么做阻止由window.getSelection()引起的循环引用?

编辑

新的演示版也适用于其他浏览器,但仍然提供错误的anchorNode: http://jsfiddle.net / fyG3H / 5 /

New demo which works in other browsers too but still gives the wrong anchorNode: http://jsfiddle.net/fyG3H/5/

使用JSON.stringify: http://jsfiddle.net/fyG3H/6/

And with JSON.stringify: http://jsfiddle.net/fyG3H/6/

Firefox似乎返回空{}而不是抛出错误。

Firefox seem to return an empty {} instead of throwing an error.

推荐答案

你需要调用 toString() on getSelection()。我 更新了您的小提琴 ,让您的行为符合您的预期。

You need to invoke toString() on getSelection(). I've updated your fiddle to behave as you'd expect.

var selection;

$('p').bind('mouseup', function() {
    selection = window.getSelection().toString();
});

$('input').bind('focus', function() {
   this.value = selection;
   console.log(selection); 
});

查看演示

编辑:

你没有得到正确的锚节点的原因是 DOMSelection 对象是通过引用传递的,当你专注于输入时,选择被清除,从而返回对应于无选择的选择默认值。解决此问题的一种方法是将 DOMSelection 属性克隆到对象并引用它。您将不再拥有原型 DOMSelection 方法,但根据您的要求,这可能就足够了。

The reason that you're not getting the correct anchor node is that the DOMSelection object is passed by reference and when you focus on the input, the selection gets cleared, thus returning the selection defaults corresponding to no selection. One way you can get around this is to clone the DOMSelection properties to an object and reference that. You won't have the prototypal DOMSelection methods any more, but depending on what you want to do this may be sufficient.

var selection, clone;

$('p').bind('mouseup', function() {
    selection = window.getSelection();
    clone = {};
    for (var p in selection) {
        if (selection.hasOwnProperty(p)) {
            clone[p] = selection[p];
        }
    }
});

$('input').bind('focus', function() {
   console.dir(clone); 
});

查看演示

这篇关于阻止JavaScript window.getSelection()循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆