JavaScript / jQuery: how to get selected text in Firefox

三世轮回 提交于 2019-12-11 08:23:30

问题


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


来源:https://stackoverflow.com/questions/20563045/javascript-jquery-how-to-get-selected-text-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!