简体   繁体   English

防止JavaScript window.getSelection()循环引用

[英]Prevent JavaScript window.getSelection() circular reference

See this demo (dependent on selectionchange event which works in Chrome only at this moment): http://jsfiddle.net/fyG3H/ 观看此演示(取决于仅在当前Chrome中有效的selectionchange事件): http : //jsfiddle.net/fyG3H/

Select some lorem ipsum text and then focus the text input. 选择一些lorem ipsum文本,然后集中文本输入。 In the console log you will see that there is a DOMSelection object. 在控制台日志中,您将看到有一个DOMSelection对象。 It has an anchorNode value of HTMLBodyElement while it should have one of Text . 它具有HTMLBodyElement的anchorNode值,而应具有Text

I didn't know why this was happening until I tried stringfying the selection object: http://jsfiddle.net/fyG3H/1/ 我不知道为什么会这样,直到我尝试对选择对象进行字符串处理: http : //jsfiddle.net/fyG3H/1/

This gives the following error: 这给出了以下错误:

Uncaught TypeError: Converting circular structure to JSON 未捕获的TypeError:将圆形结构转换为JSON

Do you know how I can prevent this circular reference caused by window.getSelection() ? 您知道如何防止由window.getSelection()引起的这种循环引用吗?

EDIT 编辑

New demo which works in other browsers too but still gives the wrong anchorNode: http://jsfiddle.net/fyG3H/5/ 新的演示也可以在其他浏览器中使用,但仍然提供了错误的anchorNode: http : //jsfiddle.net/fyG3H/5/

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

Firefox seem to return an empty {} instead of throwing an error. Firefox似乎返回一个空的{}而不是抛出错误。

You need to invoke toString() on getSelection() . 您需要在getSelection()上调用toString() 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); 
});

See demo 观看演示


EDIT: 编辑:

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. 无法获得正确的锚节点的原因是DOMSelection对象是通过引用传递的,当您专注于输入时,选择将被清除,从而返回与没有选择相对应的选择默认值。 One way you can get around this is to clone the DOMSelection properties to an object and reference that. 解决该问题的一种方法是将DOMSelection属性克隆到一个对象并对其进行引用。 You won't have the prototypal DOMSelection methods any more, but depending on what you want to do this may be sufficient. 您将不再具有原型DOMSelection方法,但是根据您要执行的操作,这可能就足够了。

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); 
});

See demo 观看演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM