2014-09-01 72 views
0

因此,我在我的網站上使用編輯工具,並將自己的按鈕和自定義樣式添加到工具欄中。我有在樣式之間切換並且獲取選定文本的功能。如何創建一個函數從選定的文本中獲取html,並找到某個元素,如< p>或< img>?如何獲取選定文本上的文本和html返回

這是我迄今爲止...

init: function(editor) { 

    var config = editor.config, 
     lang = editor.lang.format; 

    // Gets the list of tags from the settings. 
    var tags = []; //new Array(); 
    tags[0]=["red_font", "Red Font", "Name"]; 

    // Create style objects for all defined styles. 

    editor.ui.addRichCombo('dag_wygwam', 
     { 
      label : "Buttons", 
      title :"Buttons", 
      voiceLabel : "Buttons", 
      className : 'cke_format', 
      multiSelect : false, 

      panel : 
      { 
       voiceLabel : lang.panelVoiceLabel 
      }, 

      init : function() 
      { 
       this.startGroup("Buttons Functions"); 
       for (var this_tag in tags){ 
        this.add(tags[this_tag][0]; 
       } 
      }, 

      onClick : function(value) 
      { 
       console.log(editor.getSelection().getSelectedText()); 
       editor.fire('saveSnapshot'); 

       switch (value) { 
        case "red_font": value = red_font(editor.getSelection().getSelectedText()); break; 
       }      
       editor.insertHtml(value); 
       editor.fire('saveSnapshot');       
      } 
     }); 
} 
}); 

function red_font(selection){ 
} 

所以這個red_font函數必須做到以下幾點:獲取從所選文本的HTML,找到所選文本的跨度類,只有使跨度元素紅色。

回答

0
var theselectedtext = null; 
var theselectedelement = null; 
document.onmouseup = function(e) { 
e = e||event; 
// to get the selected text 
if (window.getSelection) { 
// most browsers 
theselectedtext = window.getSelection().toString(); 
} else { 
// IE9 
if (document.selection.createRange) { 
theselectedtext = document.selection.createRange().text; 
} 
} 
if (theselectedtext != null) { 
// get the last clicked element 
theselectedelement = e.target.tagName.toLowerCase(); 
} 
} 

在任何給定時間,這些選定的文本變量將包含選定的文本,並且這些元素變量將包含選定的元素。