2011-06-06 134 views
44

有了contenteditable元素我怎樣才能用我自己的html替換選定的內容?如何用contenteditable元素中的html替換選定的文本?

+0

這個問題的第二部分(「換成我自己的HTML所選文本」)中,他的問題鏈接爲未回答這是一個重複的參考。 – 2014-07-15 23:49:42

+0

我刪除了已回答的部分,以符合「每個問題的一個問題」規則。 – FakeRainBrigand 2014-07-16 00:16:20

回答

69

看到這裏的工作的jsfiddle:從Tim Down採取http://jsfiddle.net/dKaJ3/2/

function getSelectionHtml() { 
    var html = ""; 
    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()); 
      } 
      html = container.innerHTML; 
     } 
    } else if (typeof document.selection != "undefined") { 
     if (document.selection.type == "Text") { 
      html = document.selection.createRange().htmlText; 
     } 
    } 
    alert(html); 
} 

代碼:Return HTML from a user-selected text

+15

這看起來很熟悉... http://stackoverflow.com/questions/4652734/return-html-from-a-user-selection/4652824#4652824 – 2011-06-06 13:37:49

+13

重新使用來自另一個答案的代碼很好,但它會很有禮貌地提及你從哪裏得到的。 – 2011-06-06 14:35:10

+2

@Tim Down:對不起。我知道屬性代碼。我總是首先在文本編輯器中設置我的答案,並且最終鏈接到您的問題,我想我在粘貼之前並沒有複製所有內容(您不必接受我的說法)。這確實是一個誠實的錯誤,我會更新我的答案。 – 2011-06-06 15:12:05

48

獲取所選的HTML,你可以使用我寫了this question功能。要用您自己的HTML替換選擇,您可以使用this function。下面是插入一個HTML字符串而不是DOM節點的替代品功能的版本:

function replaceSelectionWithHtml(html) { 
    var range; 
    if (window.getSelection && window.getSelection().getRangeAt) { 
     range = window.getSelection().getRangeAt(0); 
     range.deleteContents(); 
     var div = document.createElement("div"); 
     div.innerHTML = html; 
     var frag = document.createDocumentFragment(), child; 
     while ((child = div.firstChild)) { 
      frag.appendChild(child); 
     } 
     range.insertNode(frag); 
    } else if (document.selection && document.selection.createRange) { 
     range = document.selection.createRange(); 
     range.pasteHTML(html); 
    } 
} 

replaceSelectionWithHtml("<b>REPLACEMENT HTML</b>"); 
+0

Nice Reaaaaaaaaaaaaaaaaaaly :) Thanks Tim +1 – Marwan 2012-11-11 11:07:35

+0

真棒,和實際回答問題的獎勵點:如何不只是得到的選擇,而是取代它。 – tobek 2014-05-15 22:01:11

+0

請定義'node'。我想我們可以刪除這行'html =(node.nodeType == 3)? node.data:node.outerHTML;' – 2014-06-25 14:06:41