JavaScript/jQuery:获取选择功能在Firefox和Chrome中不起作用

JavaScript / jQuery: get selection function not working in Firefox and Chrome

本文关键字:Firefox Chrome 不起作用 功能 jQuery 获取 选择 JavaScript      更新时间:2024-06-30

我使用以下函数在可编辑内容的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;
}

非常感谢你在这方面的帮助,蒂姆。

    function myGetSelection(){
         if(document.selection){ //IE
                return document.selection.createRange().text;
          } else{
                return window.getSelection().toString();
          }
   }