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

て烟熏妆下的殇ゞ 提交于 2019-12-11 14:34:03

问题


I am using the following function to get the selected text (i.e. text selected by the user) in a contenteditable div. This works perfect in IE 9 but not in IE 8, Firefox or Chrome (both latest versions).

Can someone here help me to modify this in a way that it works at least in Firefox and IE 8 as well (Chrome is not a must) ?

My function (working):

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;
}

Many thanks for any help with this, Tim.


回答1:


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


来源:https://stackoverflow.com/questions/20538789/javascript-jquery-get-selection-function-not-working-in-firefox-and-chrome

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