JavaScript替换选择所有浏览器

JavaScript替换选择所有浏览器

问题描述:

是否有一个简单的js函数我可以用它来代替当前文档的选择与我的一些html?JavaScript替换选择所有浏览器

例如,文档包含某个地方的<p>AHAHAHA</p>,用户选择第一个“ha”文本块。

现在我想的东西来取代这个喜欢:<span><font color="red">hoho</font></span>

当我谷歌* JavaScript的替代选择*我不能让一个简单直接的答案!

是的。下面将做它在所有主要浏览器,同时可以选择事后选择插入的内容,在意见中的要求(虽然这部分是不是IE <实现= 8):

现场演示:http://jsfiddle.net/bXsWQ/147/

代码:

function replaceSelection(html, selectInserted) { 
    var sel, range, fragment; 

    if (typeof window.getSelection != "undefined") { 
     // IE 9 and other non-IE browsers 
     sel = window.getSelection(); 

     // Test that the Selection object contains at least one Range 
     if (sel.getRangeAt && sel.rangeCount) { 
      // Get the first Range (only Firefox supports more than one) 
      range = window.getSelection().getRangeAt(0); 
      range.deleteContents(); 

      // Create a DocumentFragment to insert and populate it with HTML 
      // Need to test for the existence of range.createContextualFragment 
      // because it's non-standard and IE 9 does not support it 
      if (range.createContextualFragment) { 
       fragment = range.createContextualFragment(html); 
      } else { 
       // In IE 9 we need to use innerHTML of a temporary element 
       var div = document.createElement("div"), child; 
       div.innerHTML = html; 
       fragment = document.createDocumentFragment(); 
       while ((child = div.firstChild)) { 
        fragment.appendChild(child); 
       } 
      } 
      var firstInsertedNode = fragment.firstChild; 
      var lastInsertedNode = fragment.lastChild; 
      range.insertNode(fragment); 
      if (selectInserted) { 
       if (firstInsertedNode) { 
        range.setStartBefore(firstInsertedNode); 
        range.setEndAfter(lastInsertedNode); 
       } 
       sel.removeAllRanges(); 
       sel.addRange(range); 
      } 
     } 
    } else if (document.selection && document.selection.type != "Control") { 
     // IE 8 and below 
     range = document.selection.createRange(); 
     range.pasteHTML(html); 
    } 
} 

例子:

replaceSelection('<span><font color="red">hoho</font></span>', true); 
+0

酷!你可以添加少量的评论,比如最适合IE和其他浏览器的评论,谢谢! – 2011-03-22 16:35:26

+2

@Marco:完成... – 2011-03-22 16:44:55

+1

它不适用于Safari 5.1 for Mac – 2011-09-14 20:49:18

可以使用瘦长库 http://code.google.com/p/rangy/

然后,您可以做

var sel = rangy.getSelection(); 
var range = sel.getRangeAt(0); 

range.deleteContents(); 
var node = range.createContextualFragment('<span><font color="red">hoho</font></span>'); 
range.insertNode(node);