【问题标题】:JavaScript / jQuery: how to get selected text in FirefoxJavaScript / jQuery:如何在 Firefox 中获取选定的文本
【发布时间】:2014-01-01 00:25:37
【问题描述】:

如何在 Firefox 中获取选定的文本(在 contenteditable div 中)?最新版本就足够了,不需要覆盖旧版本。

假设我有一个 contenteditable div,如下所示,有人在那里选择了一个文本,然后点击了一个按钮,我如何将选定的文本复制到剪贴板或变量?

示例:

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

我当前的功能(在 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 '';
}

【问题讨论】:

    标签: javascript firefox contenteditable textselection getselection


    【解决方案1】:

    其他建议对我不起作用,但以下建议对我有用:

    var textArea = document.getElementById('input_text_area');
    var selectedText = textArea.value.substring(textArea.selectionStart,textArea.selectionEnd);
    

    这个other answer 链接到一些背景知识,说明为什么上述内容是必要的,以及为什么 window.getSelection() 在 Firefox 上不起作用。

    【讨论】:

      【解决方案2】:
      var selectedText = "" + window.getSelection();
      

      【讨论】:

      • 嗨蒂姆,感谢您的快速回复。您能告诉我如何更新上述功能以使其也涵盖此功能吗?我想让它在不同的浏览器中工作,这已经适用于 IE。我会更新帖子。
      • window.getSelection() 是标准化的并且可以跨浏览器工作,不要使用 document.getSelection() 因为这会在 FF 8 之前错误地返回一个字符串
      • @WaiKitKung:的确如此,但我认为没有人提到过document.getSelection()
      猜你喜欢
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2012-08-25
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      相关资源
      最近更新 更多