【问题标题】:JavaScript / jQuery: get selection function not working in Firefox and ChromeJavaScript / jQuery:获取选择功能在 Firefox 和 Chrome 中不起作用
【发布时间】:2013-12-12 08:50:02
【问题描述】:

我正在使用以下函数在 contenteditable div 中获取选定的文本(即用户选择的文本)。 这在 IE 9 中完美运行,但在 IE 8、Firefox 或 Chrome(均为最新版本)中不适用。

这里有人可以帮我修改它,使其至少在 Firefox 和 IE 8 中也能正常工作(Chrome 不是必须的)吗?

我的功能(工作):

function GetSelection() 
{
selTxt = '';

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());
        }
        selTxt = container.innerHTML;
    }
} 
else if (typeof document.selection != 'undefined') 
{
    if (document.selection.type == 'Text') 
    {
        selTxt = document.selection.createRange().htmlText;
    }
}
return selTxt;
}

非常感谢您提供的任何帮助,蒂姆。

【问题讨论】:

    标签: javascript jquery firefox internet-explorer-8 getselection


    【解决方案1】:
        function myGetSelection(){
             if(document.selection){ //IE
                    return document.selection.createRange().text;
              } else{
                    return window.getSelection().toString();
              }
       }
    

    【讨论】:

    • 谢谢!这是否意味着附加功能?
    猜你喜欢
    • 2012-02-17
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    相关资源
    最近更新 更多