2013-12-12 88 views
0

我正在使用以下函數來獲取所需文本(即由用戶選擇的文本)在contenteditable div中。 這適用於IE 9,但不適用於IE 8,Firefox或Chrome(均爲最新版本)。JavaScript/jQuery:獲取選擇功能在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; 
} 

與此的任何幫助,蒂姆非常感謝。

回答

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

謝謝!這是否意味着一個額外的功能? – user2571510

相關問題