2012-01-05 107 views
0

可能重复:
Insert text before and after the selected text in javascript插入文本之前,在所选文本后

我希望把一些指定的文本(可能在IFRAME时的designMode上)之前和之后的任何选择HTML中的文本document. document.getSelection()document.selection.createRange().text仅返回文本本身而不是位置。

无论如何要替换选定的文本?

无论如何在文档中的任意位置选择文本之前和之后插入特定文本?

回答

0

我今天早些时候回答你的一个相关问题:

https://stackoverflow.com/a/8740153/96100

而且,这里是一个答案,我在一年前发布到一个非常类似的问题,最近更新的IE 9的工作:

https://stackoverflow.com/a/4770592/96100

最后,这里是您的可编辑iframe的第二个链接答案的函数版本。它允许你指定一个文件对象:

function insertHtmlAtSelectionEnd(html, isBefore, doc) { 
    doc = doc || document; 
    var win = doc.defaultView || doc.parentWindow; 
    var sel, range, node; 
    if (win.getSelection) { 
     sel = win.getSelection(); 
     if (sel.getRangeAt && sel.rangeCount) { 
      range = sel.getRangeAt(0); 
      range.collapse(isBefore); 

      // Range.createContextualFragment() would be useful here but was 
      // until recently non-standard and not supported in all browsers 
      // (IE9, for one) 
      var el = doc.createElement("div"); 
      el.innerHTML = html; 
      var frag = doc.createDocumentFragment(), node, lastNode; 
      while ((node = el.firstChild)) { 
       lastNode = frag.appendChild(node); 
      } 
      range.insertNode(frag); 
     } 
    } else if ((sel = doc.selection) && sel.type != "Control") { 
     range = sel.createRange(); 
     range.collapse(isBefore); 
     range.pasteHTML(html); 
    } 
} 
相关问题