JavaScript / jQuery: how to get selected text in F

2019-08-04 16:09发布

问题:

how can I get the selected text (in a contenteditable div) in Firefox ? It would be enough for recent versions, no need to cover old versions.

Say I have a contenteditable div that looks like the below and someone selects a text there and then hits a button, how can I copy the selected text to the clipboard or a variable ?

Example:

<div class='editInput' id='editInput'>Some awesome text</div>

My current function (working in IE):

function GetSelection() 
{
    if (typeof window.getSelection != "undefined") 
    {
        var sel = window.getSelection();
        if (sel.rangeCount) 
        {
            var container = document.createElement('div');
            for (var i = 0, len = sel.rangeCount; i < len; ++i) 
                container.appendChild(sel.getRangeAt(i).cloneContents());
            return container.innerHTML;
        }
    }
    else if (typeof document.selection != 'undefined') 
        if (document.selection.type == 'Text') 
            return document.selection.createRange().htmlText;

    return '';
}

Thanks for any help with this, Tim.

回答1:

var selectedText = "" + window.getSelection();