Prevent JavaScript window.getSelection() circular reference

后端 未结 1 634
南笙
南笙 2021-01-25 09:33

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

Select some lorem ipsum text and then focus the

相关标签:
1条回答
  • 2021-01-25 09:51

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

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

    See demo

    0 讨论(0)
提交回复
热议问题